Django Restframework 过滤器

时间:2023-03-08 16:10:07

一、基本配置:

  1、安装:pip install django-filter

  2、将 django_filters 配置到INSTALLED-APPS中

  3、对 REST_FRAMEWORK 配置:

    REST_FRAMEWORK = {

      "DEFAULT_FILTER_BACKENDS":("django_filters.rest_framework.DjangoFilterBackend",)

    }

二、基本过滤器的使用

  from django_filters.rest_framework.DjangoFilterBackend

  在对应的View中添加配置

  class GoodLists(mixins.ListModelMixin, viewset.GenericViewSet):

    ...

    # 使用过滤器

    filter_backends = (DjangoFilterBackend,)

    # 定义需要过滤的字段

    filter_fields = ("name", "price")

三、自定义过滤器

  1、创建一个filter.py文件

  import django_filters

  from django.db.models import Q

  from .model import Goods

  class GoodsFilter(django_filters.rest_framework.FilterSet):

    pricemin = django_filters.NumberFilter(name = "shop_price", lookup_expr = "gte")

    pricemax = django_fliters.NumberFilter(name = "shop_price", lookup_expr = "lte")

    name = django_filters.CharFilter(name = "name", lookup_expr = "icontains")

    top_category = django_fllters.NumberFilter(name = "category", method = "get_top_category")

    def get_top_category(self, queryset, name, value):

      return queryset.filter(Q(category_id = value) | Q(category_parent_category_id = value))

  

    class Meta:

      model = Goods

      fields = ["pricemin", "pricemax", "name"]

    

  2、在视图中使用自定义过滤器

    from .filter import GoodsFilter

    class GoodLists(mixins.ListModelMixin, viewsets.GenericViewSet):

      ...

      filter_backends = (DjangoFilterBackends, filter.SearchFilter, filter.OrderingFilter)  # SearchFilter:搜索过滤器,OrderingFilter:排序过滤器

      filter_fields = ("name", "shop_price")

      # 自定义过滤器的使用

      filter_class = GoodsFilter

      search_fields = ("name", "good_brief")  # 搜索的内容包含在name中,或者包含在商品描述中

      ordering_fields = ("sold_num", "shop_price") # 排序