目錄django
分頁模式api
rest framework中提供了三種分頁模式:加密
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
全局配置rest
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 }
局部配置code
咱們能夠在視圖類中進行局部設置排序
class PublisherViewSet(ModelViewSet): queryset = models.Publisher.objects.all() serializer_class = PublisherModelSerializer pagination_class = PageNumberPagination # 注意不是列表(只能有一個分頁模式)
按頁碼數分頁,第n頁,每頁顯示m條數據get
例如:http://127.0.0.1:8000/api/article/?page=2&size=1it
分頁器io
class MyPageNumber(PageNumberPagination): page_size = 2 # 每頁顯示多少條 page_size_query_param = 'size' # URL中每頁顯示條數的參數 page_query_param = 'page' # URL中頁碼的參數 max_page_size = None # 最大頁碼數限制
視圖class
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分頁 page_obj = MyPageNumber() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data return Response(res)
返回帶頁碼連接的響應
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分頁 page_obj = MyPageNumber() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data return page_obj.get_paginated_response(res)
分頁,在n位置,向後查看m條數據
例如:http://127.0.0.1:8000/api/article/?offset=2&limit=2
分頁器
# offset分頁 class MyLimitOffset(LimitOffsetPagination): default_limit = 1 limit_query_param = 'limit' offset_query_param = 'offset' max_limit = 999
視圖
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分頁 page_obj = MyLimitOffset() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data return page_obj.get_paginated_response(res)
加密分頁,把上一頁和下一頁的id值記住
分頁器
# 加密分頁 class MyCursorPagination(CursorPagination): cursor_query_param = 'cursor' page_size = 1 ordering = '-id' # 重寫要排序的字段
視圖
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分頁 page_obj = MyCursorPagination() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data # return Response(res) return page_obj.get_paginated_response(res)