1. 以前django做的分页组件当数据量特别大的时候,性能不是很高,有以下三种方式处理:
a. 记录当前访问页的最后一条数据id,往后取多少条
b. 最多显示120页
c. 对页码进行加密(只显示上一页,下一页)
2.rest framework分页
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination,CursorPagination
a. 基于limit offset做分页 class P1(LimitOffsetPagination): max_limit = 3 #每页的最大条数 default_limit = 2 #每页条数 limit_query_param = ‘limit‘ offset_query_param = ‘offset‘ #简单的分页 class IndexView(views.APIView): def get(self,request,*args,**kwargs): user_list = models.UserInfo.objects.all() p1 = P1() page_user_list = p1.paginate_queryset(queryset=user_list, request=request, view=self) ser = IndexSerializer(instance=page_user_list, many=True) return Response(ser.data) # 不含上一页和下一页,要手动的在url中传参limit和offset来控制第几页 # return p1.get_paginated_response(ser.data) # 含上一页和下一页 #在公司中的分页简例 class IndexView(views.APIView): def get(self,request,*args,**kwargs): ret = BaseResponse() try: user_list = models.UserInfo.objects.all() p1 = P1() page_user_list = p1.paginate_queryset(queryset=user_list,request=request,view=self) ser = IndexSerializer(instance=page_user_list,many=True) ret.data = ser.data ret.next = p1.get_next_link() ret.*** = 看源码自己实现 except Exception as e: ret.code= 1001 ret.error = ‘xxxx错误‘ return Response(ret.__dict__) b. 基于页码的分页 class P2(PageNumberPagination): # 每页显示的数据条数 max_page_size = 5 page_size = 2 page_size_query_param = ‘size‘ # 页码 page_query_param = ‘page‘ #用法和上面是一样的 class IndexView(views.APIView): def get(self,request,*args,**kwargs): ret = BaseResponse() try: user_list = models.UserInfo.objects.all() p1 = P2() page_user_list = p1.paginate_queryset(queryset=user_list,request=request,view=self) ser = IndexSerializer(instance=page_user_list,many=True) ret.data = ser.data ret.next = p1.get_next_link() ret.*** = 看源码自己实现 except Exception as e: ret.code= 1001 ret.error = ‘xxxx错误‘ return Response(ret.__dict__) c. 基于Cursor的分页:记录最后一条数据的id,往后取多少条然后再进行加密 class P3(CursorPagination): cursor_query_param = ‘cursor‘ page_size = 2 ordering = ‘id‘ #排序 也可以写成 -id #用法和上面是一样的 class IndexView(views.APIView): def get(self,request,*args,**kwargs): ret = BaseResponse() try: user_list = models.UserInfo.objects.all() p1 = P3() page_user_list = p1.paginate_queryset(queryset=user_list,request=request,view=self) ser = IndexSerializer(instance=page_user_list,many=True) ret.data = ser.data ret.next = p1.get_next_link() ret.*** = 看源码自己实现 except Exception as e: ret.code= 1001 ret.error = ‘xxxx错误‘ return Response(ret.__dict__)