在 djangorestframework 中不请求任何页面时禁用分页

Sir*_*leh 2 django-rest-framework

我为 ListView API 编写了如下所示的分页类。

class PhotoListPagination(PageNumberPagination):
   page_size = 100
   page_size_query_param = 'page_size'
   max_page_size = 10000
Run Code Online (Sandbox Code Playgroud)

并在我的 API 视图中使用它pagination_class:

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()
Run Code Online (Sandbox Code Playgroud)

当我GET向/link/to/my/API/end-point?page=1或任何其他页码发送请求时,它工作得很好。目前,当page没有值(向 发送请求)时,它显示第 1 页。但是当我未在请求中/link/to/my/API/end-point设置密钥时,我需要获得所有结果而不分页。page

是否可以?

任何帮助将不胜感激。

Ehs*_*uri 7

这是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
Run Code Online (Sandbox Code Playgroud)

因此,如果此函数返回 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)
Run Code Online (Sandbox Code Playgroud)