我尝试根据用户的状态设置我的WebAPI的分页。如果用户is_anonymous
他不能使用查询参数设置页面大小。我尝试用一个视图类来做这个。我可以使用两个不同的视图类来限制对其中一个的访问,但我认为这不是一个好的解决方案。
查看课程:
class WeathermList(generics.ListAPIView):
queryset = WeatherMeasurements.objects.all()
serializer_class = WeatherMeasurementsSer
filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,)
filter_class = WeatherMeasurementsFilter
ordering_fields = ('measure_datetime',)
ordering = ('measure_datetime',)
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
# import ipdb
# ipdb.set_trace()
if self.request.user.is_anonymous:
self._paginator = AnonymousPaginator
else:
self._paginator = RegisteredPaginator
return self._paginator
分页课程:
class RegisteredPaginator(PageNumberPagination):
page_size = 288
page_size_query_param = 'page_size'
max_page_size = 10000
class AnonymousPaginator(PageNumberPagination):
page_size = 288
错误讯息:
File ".../env/lib/python3.5/site-packages/rest_framework/generics.py", line 172, in paginate_queryset
return self.paginator.paginate_queryset(queryset, self.request, view=self)
TypeError: paginate_queryset() missing 1 required positional argument: 'request'
property paginator
最初在课程GenericAPIView中声明。我不确定我是否正确地重新实现它。当我使用pagination_class
非常感谢任何有助于实现这一目标的帮助。
答案 0 :(得分:2)
问题是:self._paginator
需要一个paginator类实例,而不是一个类本身
应该是AnonymousPaginator()
和RegisteredPaginator()
,而不是AnonymousPaginator
,RegisteredPaginator
。
if self.request.user.is_anonymous:
self._paginator = AnonymousPaginator()
else:
self._paginator = RegisteredPaginator()