程序员

与DRF集成自定义fliter

2020-06-01  本文已影响0人  北海鲸落

主要目的:使用filter完成模糊查询

1. 使用FilterSet

  1. 执行pip install django_filter命令
  2. 导入
from django_filters import rest_framework as filters
  1. 使用FilterSet
  2. 将其添加到filterset_class视图类的参数中
  3. 使用新的FilterSet时,仅需要更改导入路径
  4. 如果要默认使用django-filter后端,请将其添加到DEFAULT_FILTER_BACKENDS设置中。
# settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'django_filters',
]

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
        ...
    ),
}

实现代码

from rest_framework import generics
from django_filters import rest_framework as filters
from myapp import Product


class ProductFilter(filters.FilterSet):
    min_price = filters.NumberFilter(field_name="price", lookup_expr='gte')
    max_price = filters.NumberFilter(field_name="price", lookup_expr='lte')

    class Meta:
        model = Product
        fields = ['category', 'in_stock', 'min_price', 'max_price']


class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [filters.DjangoFilterBackend,]
    filterset_class = ProductFilter

2. 使用 filterset_fields

filterset_fieldsFilterSet不可同时使用

实例代码

from rest_framework import generics
from django_filters import rest_framework as filters


class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_fields = ('category', 'in_stock')
上一篇下一篇

猜你喜欢

热点阅读