分散Django Rest Framework中ViewSet返回的列表

时间:2016-11-09 07:48:39

标签: python django pagination django-rest-framework

我创建了一个ViewSet类,其中包含一个重写的list方法,如下所示:

from rest_framework.response import Response
from rest_framework import viewsets

class MyViewSet(views.ViewSet):

    def list(self, request):
        return Response([
            {"id": 1},
            {"id": 2},
        ])

如何对此回复进行分页?

settings.py中,我进行了以下设置:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'LinkHeaderPagination',
    'PAGE_SIZE': 10
}

LinkHeaderPagination就是这样构建的:

from rest_framework import pagination
from rest_framework.response import Response

class LinkHeaderPagination(pagination.PageNumberPagination):
    page_size_query_param = 'page_size'

    def get_paginated_response(self, data):
        next_url = self.get_next_link()
        previous_url = self.get_previous_link()

        if next_url is not None and previous_url is not None:
            link = '<{next_url}>; rel="next", <{previous_url}>; rel="prev"'
        elif next_url is not None:
            link = '<{next_url}>; rel="next"'
        elif previous_url is not None:
            link = '<{previous_url}>; rel="prev"'
        else:
            link = ''

        link = link.format(next_url=next_url, previous_url=previous_url)
        headers = {'Link': link, 'Count': self.page.paginator.count} if link else {}

        return Response(data, headers=headers)

这适用于ModelViewSets,因为它们具有指定的查询集,但我如何对列表进行分页?

1 个答案:

答案 0 :(得分:2)

您只需要在分页符上调用get_paginated_reponse方法,而不是返回Response。如果这只是一个视图集

class MyViewSet(views.ViewSet):
    def list(self, request):
        data = [
            {"id": 1},
            {"id": 2},
        ]
        paginator = LinkHeaderPagination()
        page = paginator.paginate_queryset(data, request)
        if page is not None:
            return paginator.get_paginated_response(page)

        return Response(data)