我试图在视图集上使用不同的分页类集,具体取决于query_params。
class BlockViewSet(viewsets.ModelViewSet):
pagination_class = defaultPaginationClass
def get_queryset(self):
queryset = Block.objects.all()
user = self.request.query_params.get('user', None)
if user is no None:
queryset = queryset.filter(user=user)
return queryset
所以如果get请求是/block/
,我想使用defaultPagination类,而如果请求是/block/?user=1
,我想使用customPagination类。
答案 0 :(得分:3)
尝试重新定义paginator
属性,如果有用户查询参数,请将自定义分页类指定为self._paginator
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
user = self.request.query_params.get('user', None)
if user is not None:
self._paginator = customPaginationClass()
else:
self._paginator = self.pagination_class()
return self._paginator
最终
class BlockViewSet(viewsets.ModelViewSet):
pagination_class = defaultPaginationClass
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
user = self.request.query_params.get('user', None)
if user is not None:
self._paginator = customPaginationClass()
else:
self._paginator = self.pagination_class()
return self._paginator
def get_queryset(self):
queryset = Block.objects.all()
user = self.request.query_params.get('user', None)
if user is no None:
queryset = queryset.filter(user=user)
return queryset