Django Rest Framework会覆盖viewset list()方法,而不会失去filter_backends功能

时间:2018-07-20 01:54:48

标签: python django django-rest-framework

我有一个视图集,并且覆盖了list()方法,但是按字段进行的过滤停止工作。如何从代码中调用过滤选项:

这是我的观点:

 class SupplementViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.Product.objects.filter()
    serializer_class = serializers.SuplementSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    search_fields = ('hotel', 'name')
    filter_fields = ('id', 'hotel', 'name')

    def perform_create(self, instance):
        instance.save(product_type=models.Product.SUPPLEMENT)

    def list(self, request, pk=None):
        if pk == None:
            supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT)
        else:
            supplements =  models.Product.objects.get(product_type=models.Product.SUPPLEMENT, id=pk)

        page = self.paginate_queryset(supplements)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(page, many=True)
        result_set = serializer.data

        return Response(result_set)

    def get_result_set(self, supplements):
        result_set = serializers.ProductSerializer(supplements, many=True).data

        return result_set

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

def list(self, request, pk=None):
    if pk == None:
        supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT)
    else:
        supplements =  models.Product.objects.filter(product_type=models.Product.SUPPLEMENT, id=pk)

    supplements= self.filter_queryset(supplements )
    page = self.paginate_queryset(supplements)

self.filter_queryset(queryset)是您所需要的,但它必须接受queryset。

答案 1 :(得分:2)

查看list方法的实际实现会有所帮助:

http://www.cdrf.co/3.9/rest_framework.viewsets/ReadOnlyModelViewSet.html#list

您可以直接使用self.filter_queryset方法(该方法继承自GenericAPIView中的viewsets.ModelViewSet)。在极少数情况下,您将需要覆盖self.filter_queryset方法。

答案 2 :(得分:0)

Ykh和Akshay Anurag的答案都是正确的,为简单起见,您可以简单地致电:

filter_queryset(queryset)

在致电之前

paginate_queryset(filtered_queryset)