我有一个基于类的视图,用于从django通用视图ListAPIView继承的文本消息。从继承的类名中可以看出,视图被用作带有分页的API(来自Django Rest框架(。
我想关闭某些特定查询的分页,但是,即使我试图通过这个堆栈溢出问题关闭所有查询的分页(关闭Django Rest Framework ModelViewSet的自动分页(,我也会收到以下错误:
RuntimeError: Do not evaluate the `.queryset` attribute directly, as the result will be cached and reused between requests. Use `.all()` or call `.get_queryset()` instead.
我正在覆盖视图中的get_queryset((方法,但通过将paginator_class变量设置为None,我收到了此错误。如有任何帮助,我们将不胜感激。这里有一些代码:
view.py:
class TextMessageView(generics.ListAPIView):
queryset = TextMessage.objects.all()
serializer_class = TextMessageSerializer
pagination_class = None
def get_queryset(self):
"""
If a phone number is included in the url query, return only the text messages sent by that number in the
queryset, otherwise return all text messages.
:return: A Django queryset with a variable number of text messages.
"""
from_phone_num = self.request.query_params.get('from_phone_number', None)
distinct_nums = self.request.query_params.get('distinct_numbers', None)
all_msgs = self.request.query_params.get('all_messages', None)
if from_phone_num:
return TextMessage.objects.filter(from_phone_number=from_phone_num)
elif distinct_nums == 'True':
return TextMessage.objects.order_by('from_phone_number', '-date_of_message').distinct('from_phone_number')
elif all_msgs == 'True':
return self.queryset
else:
raise Http404
Django Rest Frameworks: ListAPIView.py
class ListAPIView(mixins.ListModelMixin,
GenericAPIView):
"""
Concrete view for listing a queryset.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
Django Rest Frameworks: mixins.py
class ListModelMixin:
"""
List a queryset.
"""
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_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)
你必须查找GenericAPIView.py,因为它太大了
查看错误消息,在您的get_queryset方法中,您可以尝试更改吗
elif all_msgs == 'True':
return self.queryset
至
elif all_msgs == 'True':
return self.queryset.all()