首页 > 解决方案 > 如何在 django 视图中设置分页?

问题描述

如何在这个基于函数的视图中设置分页,我尝试了所有默认的 django_pagination 但我没有得到任何帮助。

class Order_ListAPIView(APIView):

   def get(self,request,format=None):

       if request.method == 'GET':
           cur,conn = connection()
           order_query = ''' SELECT * FROM orders'''
           order_detail_query = ''' SELECT * FROM order_details'''

           with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:

               cursor.execute(order_query)
               order_result = cursor.fetchall()
               order_data = list(order_result)

           ...
            ... #rest_code
             ...


           return Response({"order_data":order_data},status=status.HTTP_200_OK)
       else:
           return Response(status=status.HTTP_400_BAD_REQUEST)

标签: sqldjangodjango-rest-frameworkpagination

解决方案


作为建议,您可以使用 django-rest-framework 通用视图分页和 django orm

分页.py

from rest_framework.pagination import PageNumberPagination
class OrderPagination(PageNumberPagination):
    page_size = 20 #default

视图.py

from rest_framework.generics import ListAPIView
from .paginations import OrderPagination
from .models import Order

class OrderListAPIView(ListAPIView):
   serializer_class = your_serializer_class
   pagination_class = OrderPagination
   queryset = Order.objects.all()

推荐阅读