分页两类,一类是普通的分页,另外是加密的分页(页码加密并且只能跳转上页与下一页)
核心源代码:results = list(queryset[offset:offset + self.page_size + 1])
普通分页:from rest_framework.pagination import PageNumberPagination
对于指定的参数,可全局配置或者继承PageNumberPagination类进行重写配置
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)
对于加密翻页 CursorPaginationfrom 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方法
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