django restframework如何获取过滤的查询集

时间:2019-07-24 06:43:37

标签: django django-rest-framework

这是示例代码。在实际环境中,有很多查询参数。

views.py

class EavValueViewSet(PandasMixin, viewsets.ModelViewSet):
    serializer_class = serializers.EavValueSerializer
    queryset = models.EavValue.objects.all()
    pagination_class = None
    filter_backends = (filters.DjangoFilterBackend, OrderingFilter, SearchFilter,)
    search_fields = ('value',)
    filter_class = EavValueFilter
    ordering_fields = ('timestamp',)
    ordering = ('-timestamp',)

我搜索了值,网址为 http://localhost:8000/api/eav_value/?search=test,然后我想返回另一个响应。

如何获取过滤后的查询集。

1 个答案:

答案 0 :(得分:0)

如果要获取过滤的查询集或尝试执行任何操作,可以覆盖mixins.ListModelMixin中的viewsets.ModelViewSet。在我的示例中,我仅在控制台中打印它。

class EavValueViewSet(PandasMixin, viewsets.ModelViewSet):
    serializer_class = serializers.EavValueSerializer
    queryset = models.EavValue.objects.all()
    pagination_class = None
    filter_backends = (filters.DjangoFilterBackend, OrderingFilter, SearchFilter,)
    search_fields = ('value',)
    filter_class = EavValueFilter
    ordering_fields = ('timestamp',)
    ordering = ('-timestamp',)

    def list(self, request, *args, **kwargs):
       queryset = self.filter_queryset(self.get_queryset())
       # this is filtered queryset
       print(queryset)
       page = self.paginate_queryset(queryset)
       if page is not None:
           serializer = self.get_serializer(page, many=True)
           return self.get_paginated_response(serializer.data)

       serializer = self.get_serializer(queryset, many=True)
       return Response(serializer.data)