本文介绍了在Django Rest Framework中对ViewSet返回的列表进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个 ViewSet
类,该类具有覆盖的 list
方法,如下所示:
I have created a ViewSet
class with a overridden list
method like this:
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},
])
我如何对这个回复进行分页?
How do I paginate this response?
在 settings.py
中,我进行了以下设置:
In settings.py
I've the following setup:
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
一起使用非常好,因为它们具有指定的查询集,但是我如何对列表进行分页?
This works great with ModelViewSets
since they have a specified queryset, but how do I paginate a list?
推荐答案
您只需要在分页器上调用 get_paginated_reponse
方法,而不是返回 Response
.如果这仅仅是一个视图集
You just need to call get_paginated_reponse
method on paginator instead of returning Response
. If this is a single viewset only
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)
这篇关于在Django Rest Framework中对ViewSet返回的列表进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!