分頁兩類,一類是普通的分頁,另外是加密的分頁(頁碼加密而且只能跳轉上頁與下一頁)
核心源代碼:
results = list(queryset[offset:offset + self.page_size + 1])
python
普通分頁:
from rest_framework.pagination import PageNumberPagination
對於指定的參數,可全局配置或者繼承PageNumberPagination類進行重寫配置api
class AllAccounts(APIView): def get(self, request): accounts = AccountModel.objects.all() pg = PageNumberPagination() pg_data = pg.paginate_queryset(queryset=accounts,request=request,view=self) serializers = AccountSerializers(pg_data, many=True, context={'request': request}) return pg.get_paginated_response(serializers.data)
對於加密翻頁 CursorPagination
from rest_framework.pagination import CursorPagination
加密
class MyCursorPagination(CursorPagination): cursor_query_param = 'cursor' # 翻頁參數 page_size = 2 ordering = 'id' #默認是根據 -create 排序 page_size_query_param = None class AllAccounts(APIView): def get(self, request): accounts = AccountModel.objects.all() pg = MyCursorPagination() pg_data = pg.paginate_queryset(queryset=accounts,request=request,view=self) serializers = AccountSerializers(pg_data, many=True, context={'request': request}) return pg.get_paginated_response(serializers.data) """ 對於response,會攜帶上下翻頁的頁碼 例如: "next": "http://127.0.0.1:8000/api/accounts/?cursor=cD00", "previous": "http://127.0.0.1:8000/api/accounts/?cursor=cj0xJnA9Mw%3D%3D", """
對於獲取頁碼的get_page_size方法rest
def get_page_size(self, request): if self.page_size_query_param: try: return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) #query_params內部封裝的 調用self._request.GET方法 except (KeyError, ValueError): pass return self.page_size