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

时间:2018-09-24 07:23:00

标签: django-rest-framework

我为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>

有可能吗?

任何帮助将不胜感激。

2 个答案:

答案 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)