5.10.drf的过滤

通过属性过滤

goods/views.py

class GoodsCategoryViewSet(ListModelMixin, GenericViewSet):
    """
    获取商品类型列表
    """
    queryset = GoodsCategory.objects.all()
    ...

通过函数过滤

goods/views.py

class GoodsCategoryViewSet(ListModelMixin, GenericViewSet):
    """
    获取商品类型列表
    """
    queryset = GoodsCategory.objects.all()
    ...
    def get_queryset(self):
        return GoodsCategory.objects.filter(category_type__gt=1)

更复杂的函数过滤

goods/views.py

class GoodsCategoryViewSet(ListModelMixin, GenericViewSet):
    """
    获取商品类型列表
    """
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategorySerializer
    pagination_class = LargeResultsSetPagination

    def get_queryset(self):
        queryset = GoodsCategory.objects.all()
        category_type_min = self.request.query_params.get('category_type_min', 0)
        if category_type_min:
            queryset = queryset.filter(category_type__gt=int(category_type_min))
        return queryset

django-filter

简化传统filter

goods/views.py

from django_filters.rest_framework import DjangoFilterBackend

class GoodsCategoryViewSet(ListModelMixin, GenericViewSet):
    """
    获取商品类型列表
    """
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategorySerializer
    pagination_class = LargeResultsSetPagination
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('category_type', 'name')

存在问题:无法模糊匹配

自定义django-filter

goods/filters.py

import django_filters

from goods.models import GoodsCategory


class GoodsCategoryFilter(django_filters.FilterSet):
    """
    商品的过滤类
    """
    category_type_min = django_filters.NumberFilter(field_name='category_type', lookup_expr='gte')
    category_type_max = django_filters.NumberFilter(field_name='category_type', lookup_expr='lte')
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains') # 加i忽略大小写

    class Meta:
        model = GoodsCategory
        fields = ['category_type_min', 'category_type_max', 'name']

goods/views.py

class GoodsCategoryViewSet(ListModelMixin, GenericViewSet):
    """
    获取商品类型列表
    """
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategorySerializer
    pagination_class = LargeResultsSetPagination
    filter_backends = (DjangoFilterBackend,)
    filter_class = GoodsCategoryFilter

Last updated

Was this helpful?