我为ListView API编写了以下分页类。
class PhotoListPagination(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
max_page_size = 10000
并在pagination_class
的API视图中使用它:
class UserSinglePhotoAPIView(ListAPIView):
model = Photo
serializer_class = PhotoSerializer
pagination_class = PhotoListPagination
def get_queryset(self):
return Profile.objects.get(auth_user__username=self.kwargs['username']).get_single_photos()
当我向GET
或其他任何页码发送/link/to/my/API/end-point?page=1
请求时,它运行良好。当前,当page
没有值(向/link/to/my/API/end-point
发送请求)时,它会显示第1页。但是,当我未在请求中设置page
键时,我需要所有结果都没有分页。 / p>
有可能吗?
任何帮助将不胜感激。
答案 0 :(得分:1)
您可以在list
中覆盖UserSinglePhotoAPIView
方法,并且仅在提供页面查询参数时进行分页。否则返回全部。
类似的东西:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
if 'page' in request.query_params:
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)
答案 1 :(得分:1)
这是通用视图中的paginate_queryset
方法,
def paginate_queryset(self, queryset):
"""
Return a single page of results, or `None` if pagination is disabled.
"""
if self.paginator is None:
return None
return self.paginator.paginate_queryset(queryset, self.request, view=self
因此,如果此函数返回None,则ListView将返回包含所有结果的单个页面,因此请按以下方法重写此方法:
class UserSinglePhotoAPIView(ListAPIView):
...
...
def paginate_queryset(self, queryset):
if self.paginator and self.request.query_params.get(self.paginator.page_query_param, None) is None:
return None
return super().paginate_queryset(queryset)