python Django Rest框架在自定义get函数中获取过滤后的查询集

3htmauhk  于 2023-02-18  发布在  Python
关注(0)|答案(1)|浏览(103)

所以我有一个APIView,如下所示:

from rest_framework.views import APIView

class MyAPIView(APIView):
    queryset = MyObject.objects.all()
    filter_backends = [MyCustomFilterBackend, DjangoFilterBackend]
    filterset_fields = ["field1", "field2"]

    def get(self, request):
        s = StatManager(self.queryset)
        return Response(s.dashboard())

在这里,我使用MyCustomFilterBackendDjangoFilterBackend过滤一堆内容,我的目标是将过滤后的查询集提供给StatManager,以便它为 Jmeter 板生成统计信息。
目前,s = StatManager(self.queryset)没有考虑过滤器。我如何在get函数中提供过滤后的查询集?
我看了DRF文档。我期待APIView有一些像get_filtered_queryset()的功能。
我读了Filters of Django REST Framework inside GET function?DJango filter_queryset,但它们没有足够的答案。

x33g5p2x

x33g5p2x1#

尝试在get()方法内部的filter_queryset()方法中使用self.queryset,以便:

from rest_framework.views import APIView

class MyAPIView(APIView):
    queryset = MyObject.objects.all()
    filter_backends = [MyCustomFilterBackend, DjangoFilterBackend]
    filterset_fields = ["field1", "field2"]

    def filter_queryset(self, queryset):
        for backend in list(self.filter_backends):
            queryset = backend().filter_queryset(self.request, queryset, self)
        return queryset

    def get(self, request):
        queryset = self.filter_queryset(self.queryset)
        s = StatManager(queryset)
        return Response(s.dashboard())

相关问题