虽然 rayy 提到的方式是可能的,但 django-rest-framework 可以通过一些额外的功能在内部处理这个问题,使使用 API 变得更加容易。(*note django-rest-framework 的分页是从 django.core.paginator 的 Django 分页器构建的)
在您引用的内容之后是解决此问题的关键信息:
仅当您使用通用视图或视图集时,才会自动执行分页。如果您使用的是常规 APIView,则需要自己调用分页 API 以确保返回分页响应。有关示例,请参阅 mixins.ListMixin 和 generics.GenericAPIView 类的源代码。
对那里所说的内容进行轻微修正:查看 ListModelMixin。
如果你去这两个链接,你可以看到上述文件的源代码:
generics.py
mixins.py
您需要做的是包含类似以下内容以使分页在 APIView 中工作(**注意:此代码未经测试,但想法是正确的。还有一种更好的编写方法,而不必包含代码在每一种观点中,但我将把它留给你,以使我的回答简短易懂):
from __future__ import absolute_import
# if this is where you store your django-rest-framework settings
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Cart
class CartView(APIView):
pagination_class = settings.DEFAULT_PAGINATION_CLASS
def get(self, request, format=None):
#assuming every other field in the model has a default value
cart = Cart.objects.get_or_create(user=request.user)
#for a clear example
cart_details = Cart.objects.all()
page = self.paginate_queryset(cart_details)
if page is not None:
serializer = CartDetailSerializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = CartDetailSerializer(cart_details, many=True)
return Response(serializer.data)
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
self._paginator = self.pagination_class()
return self._paginator
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)
def get_paginated_response(self, data):
"""
Return a paginated style `Response` object for the given output data.
"""
assert self.paginator is not None
return self.paginator.get_paginated_response(data)
我希望这对你和其他看到这篇文章的人有更多帮助。