我创建了一个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
,因为它们具有指定的查询集,但我如何对列表进行分页?
答案 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)