gpt4 book ai didi

django - 使用API​​-View在Django-Rest-Framework中进行分页

转载 作者:行者123 更新时间:2023-12-03 22:55:15 26 4
gpt4 key购买 nike

我目前有一个API View 设置,如下所示:

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的文档中,我发现了这一点:

If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response.



没有提供有关如何对常规APIView API进行分页的示例。

任何人都可以发表我可以在上述情况下使用的示例。

谢谢。

最佳答案

使用常规APIView时,您需要使用Django自己的Paginator类。

Django Pagination in Views

在您的情况下,您可以在将查询集发送给序列化程序之前对其进行分页。

像这样:

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)

希望这可以帮助。

关于django - 使用API​​-View在Django-Rest-Framework中进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29071312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com