1. 程式人生 > >DRF 分頁

DRF 分頁

color article 查看 大頁 參數 XML turn mit mod

rest framework中提供三種分頁:

from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination

全局配置文件:

REST_FRAMEWORK = {
    PAGE_SIZE: 2
}

1. 分頁,看第n頁,每頁顯示n條數據

例如:http://127.0.0.1:8000/api/article/?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 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)

2. 分頁,在n個位置,向後查看n條數據

例如: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)

3.加密分頁,把上一頁和下一頁的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)

DRF 分頁