0
我嘗試根據用戶的狀態設置我的WebAPI的分頁。如果用戶is_anonymous
他不應該能夠使用查詢參數設置頁面大小。我試圖用一個視圖類來做到這一點。我可以用兩個不同的視圖類來限制對其中一個視圖的訪問,但我認爲這不是一個好的解決方案。根據用戶類型改變分頁與Django休息框架
視圖類:
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
任何幫助獲得這個工作非常感謝。
哦,我的上帝,多麼尷尬。非常感謝你!你認爲這樣使用分頁是個好主意嗎? –
@ChristianRapp是的,事實上,這是最好的方式。實際上,我在這個問題中推薦了幾個小時前的方法:http://stackoverflow.com/questions/38988272/django-rest-framework-drf-how-to-set-pagination-class-depending-on-query -param/38989390#38989390 – levi