DRF的分页
DRF提供的三种分页
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
全局配置
REST_FRAMEWORK = { 'PAGE_SIZE': 2 }
第一种 PageNumberPagination 看第n页,每页显示n条数据
http://127.0.0.1:8000/book?page=2&size=1
class MyPageNumber(PageNumberPagination): page_size = 2 # 每页显示多少条 page_size_query_param = 'size' # URL中每页显示条数的参数 page_query_param = 'page' # URL中页码的参数 max_page_size = None # 最大页码数限制
class BookView(APIView): def get(self, request): book_list = Book.objects.all() # 分页 page_obj = MyPageNumber() page_article = page_obj.paginate_queryset(queryset=book_list, request=request, view=self) ret = BookSerializer(page_article, many=True) return Response(ret.data)
class BookView(APIView): def get(self, request): book_list = Book.objects.all() # 分页 page_obj = MyPageNumber() page_article = page_obj.paginate_queryset(queryset=book_list, request=request, view=self) ret = BookSerializer(page_article, many=True) # return Response(ret.data) # 返回带超链接 需返回的时候用内置的响应方法 return page_obj.get_paginated_response(ret.data)
第二种 LimitOffsetPagination 在第n个位置 向后查看n条数据
http://127.0.0.1:8000/book?offset=2&limit=1
class MyLimitOffset(LimitOffsetPagination): default_limit = 1 limit_query_param = 'limit' offset_query_param = 'offset' max_limit = 999
# 视图和上面的大体一致 # 只有用的分页类不同,其他都相同 class BookView(APIView): def get(self, request): book_list = Book.objects.all() # 分页 page_obj = MyLimitOffset() page_article = page_obj.paginate_queryset(queryset=book_list, request=request, view=self) ret = BookSerializer(page_article, many=True) # return Response(ret.data) # 返回带超链接 需返回的时候用内置的响应方法 return page_obj.get_paginated_response(ret.data)
第三种 CursorPagination 加密游标的分页 把上一页和下一页的id记住
class MyCursorPagination(CursorPagination): cursor_query_param = 'cursor' page_size = 1 ordering = '-id'
class BookView(APIView): def get(self, request): book_list = Book.objects.all() # 分页 page_obj = MyCursorPagination() page_article = page_obj.paginate_queryset(queryset=book_list, request=request, view=self) ret = BookSerializer(page_article, many=True) # return Response(ret.data) # 返回带超链接 需返回的时候用内置的响应方法 return page_obj.get_paginated_response(ret.data)