[英]Change pagination based on user type with django rest framework
I try to set the pagination of my WebAPI based on the status of a User. 我尝试根据用户的状态设置WebAPI的分页。 If the user
is_anonymous
he should not be able to set the page size with a query parameter. 如果用户
is_anonymous
他应该不能使用查询参数设置页面大小。 I try to do this with one view class. 我尝试通过一个视图类来做到这一点。 I could do it with two different view classes and limit the access to one of them, but I think this is not a good solution.
我可以使用两个不同的视图类来做到这一点,并限制对其中一个视图类的访问,但是我认为这不是一个好的解决方案。
View Class: 查看类别:
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
Pagination classes: 分页课程:
class RegisteredPaginator(PageNumberPagination):
page_size = 288
page_size_query_param = 'page_size'
max_page_size = 10000
class AnonymousPaginator(PageNumberPagination):
page_size = 288
Error message: 错误信息:
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'
The property paginator
is originally declared in class GenericAPIView . property paginator
器最初在类GenericAPIView中声明。 I am not sure if I reimplement it correctly. 我不确定是否可以正确地重新实现它。 Both Custom pagination classes of mine are working when I set them using
pagination_class
当我使用
pagination_class
设置它们时,我的两个自定义分页类都可以工作
Any help to get this working is greatly appreciated. 非常感谢您的协助,以使这项工作正常进行。
The problem is: self._paginator
needs a paginator class instance, not a class itself 问题是:
self._paginator
需要一个paginator类实例,而不是一个类本身
It should be AnonymousPaginator()
and RegisteredPaginator()
, not AnonymousPaginator
, RegisteredPaginator
. 它应该是
AnonymousPaginator()
和RegisteredPaginator()
,而不是AnonymousPaginator
, RegisteredPaginator
。
if self.request.user.is_anonymous:
self._paginator = AnonymousPaginator()
else:
self._paginator = RegisteredPaginator()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.