我目前有一个API视图设置如下:
class CartView(APIView):
authentication_classes = [SessionAuthentication, TokenAuthentication]
permission_classes = [IsAuthenticated, ]
api_view = ['GET', 'POST']
def get(self, request, format=None):
try:
cart = request.user.cart
except Cart.DoesNotExist:
cart = Cart.objects.create(user=request.user)
cart_details = cart.cart_details.all()
serializer = CartDetailSerializer(cart_details, many=True, fields=['id', 'item', 'quantity', 'product_type'])
return Response(serializer.data)
此处CartDetailSerializer
是普通的ModelSerializer。
我想分页这个API。但是,在DRF的文档中,我发现了这个:
如果您使用常规APIView,则需要自己调用分页API以确保返回分页响应。
没有提供有关如何对常规APIView API进行分页的示例。
任何人都可以发布一个我可以在上面的场景中使用的例子。
感谢。
答案 0 :(得分:21)
虽然rayy提到的方式是可能的,但django-rest-framework可以在内部处理这一点,并提供一些额外的功能,使您可以更轻松地使用API。 (*注意django-rest-framework的分页是从django.core.paginator的Django paginator构建的)
在你引用的内容之后是解决这个问题的关键信息:
只有在使用通用视图或视图集时,才会自动执行分页。如果您使用常规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)
我希望这对你和遇到这篇文章的其他人有更多帮助。
答案 1 :(得分:12)
使用常规APIView时,您需要使用Django自己的Paginator类。
在您的情况下,您可以在将查询集发送到序列化程序之前对其进行分页。
这样的事情:
def get(self, request, format=None):
try:
cart = request.user.cart
except Cart.DoesNotExist:
cart = Cart.objects.create(user=request.user)
cart_details = cart.cart_details.all()
paginator = Paginator(cart_details, 10)
page = request.GET.get('page')
try:
cart_details = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
cart_details = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
cart_details = paginator.page(paginator.num_pages)
serializer = CartDetailSerializer(cart_details, many=True, fields=['id', 'item', 'quantity', 'product_type'])
return Response(serializer.data)
希望这有帮助。
答案 2 :(得分:0)
我正在使用DRF版本3.6.2。 你不需要编写那么多代码。只需使用这个简单的步骤。
class ProductPagination(PageNumberPagination):
page_size = 5
class product_api(generics.ListCreateAPIView):
queryset = Products.objects.all()
serializer_class = product_serilizer
pagination_class = ProductPagination
如果您想通过获取方法来搜索功能,可以在下面编写代码
class ProductPagination(PageNumberPagination):
page_size = 5
class product_api(generics.ListCreateAPIView):
queryset = Products.objects.all()
serializer_class = product_serilizer
pagination_class = SearchProductPagination
def get_queryset(self):
qs = super(product_search_api,self).get_queryset()
searched_product = self.request.query_params.get('searched_product',None)
if search:
qs = Products.objects.filter(Q(product_name__icontains= searched_product))
return qs
答案 3 :(得分:0)
我更喜欢扩展Paginator类,这是它的外观:
from rest_framework import status
from rest_framework.exceptions import NotFound as NotFoundError
from rest_framework.pagination import PageNumberPagination # Any other type works as well
from rest_framework.response import Response
from rest_framework.views import APIView
class CustomPaginator(PageNumberPagination):
page_size = 10 # Number of objects to return in one page
def generate_response(self, query_set, serializer_obj, request):
try:
page_data = self.paginate_queryset(query_set, request)
except NotFoundError:
return Response({"error": "No results found for the requested page"}, status=status.HTTP_400_BAD_REQUEST)
serialized_page = serializer_obj(page_data, many=True)
return self.get_paginated_response(serialized_page.data)
class CartView(APIView):
def get(self, request, format=None):
cart_details = Cart.objects.filter(user=request.user) # or any other query
paginator = CustomPaginator()
response = paginator.generate_response(cart_details, CartDetailSerializer, request)
return response