英文:
Django Rest Framework get filtered queryset in custom get function
问题
我有一个名为MyAPIView
的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())
在这里,我使用MyCustomFilterBackend
和DjangoFilterBackend
来过滤很多内容。我的目标是将经过筛选的查询集提供给StatManager
,以便它生成仪表板的统计信息。
目前,s = StatManager(self.queryset)
不考虑筛选条件。我该如何在我的get
函数中提供经过筛选的查询集?
我阅读了DRF文档。我期望APIView
有类似get_filtered_queryset()
的函数。
我阅读了在GET函数内部使用Django REST Framework的过滤器和DJango filter_queryset,但它们没有提供令人满意的答案。
英文:
So I have an APIView
like this:
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())
where I filter bunch of stuff using MyCustomFilterBackend
and DjangoFilterBackend
. My goal is to give the filtered queryset to StatManager
so it generates stats for the dashboard.
Currently, s = StatManager(self.queryset)
does not take filters into account. How can I provide the filtered queryset in my get
function?
I read the DRF documentation. I was expecting for APIView
to have some function like get_filtered_queryset()
.
I read Filters of Django REST Framework inside GET function?
and DJango filter_queryset but they have no adequate answers.
答案1
得分: 1
尝试在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())
在这段代码中,将self.queryset
用于 filter_queryset()
方法内的查询操作。
英文:
Try to use self.queryset
in filter_queryset()
method inside get()
method so:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论