python-django rest framework框架之分頁
阿新 • • 發佈:2018-02-27
link 自己實現 -i man model 三種 imp *** efault
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__)
python-django rest framework框架之分頁