关于django过滤器的使用
最近项目中要做分类筛选,其实已经做了这个功能,但是有一个字段是MultiSelectField类型,包含多个值,用户提交的数据是单个值,无法查询出结果,
所以用到了自定义过滤
原代码
class InvestmentAgencyViewSet(viewsets.ModelViewSet): """ Viewset for investcase model """ queryset = InvestmentAgency.objects.is_public() serializer_class = InvestmentAgencySerializer permission_classes = ( permissions.DjangoModelPermissions, ) filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filter_fields = ('id', 'name', 'sector_type', 'investment_stage', 'country') search_fields = ('name', ) ordering_fields = ('name', 'founded_time') def list(self, request, *args, **kwargs): """ add country data """ queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) res = add_country_in_list(serializer.data) return self.get_paginated_response(res) serializer = self.get_serializer(queryset, many=True) res = add_country_in_list(serializer.data) return Response(res)
自定义过滤器后代码
#自定义的过滤器类,继承django_filters.rest_framework.FilterSet class InvestFilter(django_filters.rest_framework.FilterSet): sector_type =django_filters.CharFilter(lookup_expr='icontains') class Meta: model = InvestmentAgency fields = ['id', 'name', 'sector_type', 'investment_stage', 'country']
class InvestmentAgencyViewSet(viewsets.ModelViewSet): """ Viewset for investcase model """ queryset = InvestmentAgency.objects.is_public() serializer_class = InvestmentAgencySerializer permission_classes = ( permissions.DjangoModelPermissions, ) filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filter_fields = ('id', 'name', 'sector_type', 'investment_stage', 'country') search_fields = ('name', ) ordering_fields = ('name', 'founded_time') filter_class = InvestFilter def list(self, request, *args, **kwargs): """ add country data """ queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) res = add_country_in_list(serializer.data) return self.get_paginated_response(res) serializer = self.get_serializer(queryset, many=True) res = add_country_in_list(serializer.data) return Response(res)
其余django-filter使用参考