django rest framework 分頁


DRF提供了3種分頁方式
基礎分頁:PageNumberPagination(夠用,常用,採用該方法)
Offset分頁類:LimitOffsetPagination(偏移量查詢分頁)
加密分頁:CursorPagination(只能通過點“上一頁”和下一頁訪問數據)

新建自定義分頁pager.py文件

基礎分頁

from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
from rest_framework.response import Response

'''
自定義分頁:基礎分頁
http://127.0.0.1:8000/api/v1/work_order?size=10&page=1
'''


class MyPagination(PageNumberPagination):
    # 指定每一頁的個數,默認爲配置文件裏面的PAGE_SIZE,也可以在settings.py中添加全局配置('PAGE_SIZE': 10 )
    page_size = 10

    # 可以讓前端指定每頁個數,指定size做爲key顯示每頁個數,可自定義key
    page_size_query_param = 'size'

    # 控制每頁最大顯示條數:(這個控制僅限制於路徑後拼接設置size=1000後,對其進行限制)
    max_page_size = 100

    # 可以讓前端指定頁碼數,默認是page做爲key顯示頁數,可自定義key
    page_query_param = 'page'

    # # 指定返回格式,根據需求返回一個總頁數,數據存在results字典裏返回
    # def get_paginated_response(self, data):
    #     from collections import OrderedDict
    #     return Response(OrderedDict([('count', self.page.paginator.count), ('data', data)]))

在方法中調用基礎分頁

    def get(self, request):
        # 自定義response result,用於前後端分離
        result = {'count': '', 'data': '', 'meta': {'msg': 'OK', 'status': 200}}
        try:
            # 基本分頁
            workorder = WorkOrderInfo.objects.all().order_by('id')
            count = WorkOrderInfo.objects.count()
            # 創建對象
            pg = MyPagination()
            # 獲取分頁數據
            page_query = pg.paginate_queryset(queryset=workorder, request=request, view=self)
            # 序列化數據
            workorder_ser = WorkOrderSerializer(page_query, many=True)

            result['data'] = workorder_ser.data
            result['count'] = count

        except Exception as e:
            result['meta']['msg'] = '獲取數據失敗'
            result['meta']['status'] = 500
        return Response(result)

這裏展示第1頁,每頁2條

在這裏插入圖片描述

Offset分頁

'''
自定義分頁:Offset分頁類
PS:http://127.0.0.1:8000/api/v1/work_order?limit=10&offset=20
'''
class MyLimitOffsetPagination(LimitOffsetPagination):
    # 默認從offset偏移位置往後取幾個
    default_limit = 10
    # 每頁可顯示的條數,可自定義key
    limit_query_param = 'limit'
    # offset(起始位置),從設置的offset值那個位置往後拿limit值的記錄
    offset_query_param = 'offset'
    # # 設置最大獲取條數
    max_limit = 20

    # def get_paginated_response(self, data):
    #     from collections import OrderedDict
    #     return Response(OrderedDict([('count', self.count), ('data', data)]))

在方法中調用offset分頁

    def get(self, request):
        # 自定義response result,用於前後端分離
        result = {'count': '', 'data': '', 'meta': {'msg': 'OK', 'status': 200}}
        try:
            # offset分頁
            workorder = WorkOrderInfo.objects.all().order_by('id')
            count = WorkOrderInfo.objects.count()
            pg = MyLimitOffsetPagination()
            page_query = pg.paginate_queryset(queryset=workorder, request=request, view=self)
            workorder_ser = WorkOrderSerializer(page_query, many=True)

            result['data'] = workorder_ser.data
            result['count'] = count

        except Exception as e:
            result['meta']['msg'] = '獲取數據失敗'
            result['meta']['status'] = 500
        return Response(result)

這裏展示從第5條開始,往後看3條

在這裏插入圖片描述

加密分頁


'''
自定義分頁:加密分頁
加密分頁方式,只能通過點“上一頁”和下一頁訪問數據
'''


class MyCursorPagination(CursorPagination):
    cursor_query_param = "cursor"
    # 每頁顯示2個數據
    page_size = 2
    # 排序
    ordering = 'id'
    page_size_query_param = None
    max_page_size = None

在方法中調用加密分頁

加密方法不能按照上兩種常規方法做,需要通過return get_paginated_response 方法來獲取上下頁的加密頁碼,只有通過該頁碼才能訪問對應頁面。這裏因爲暫時用不到就先放下。

    def get(self, request):
        # 自定義response result,用於前後端分離
        result = {'count': '', 'data': '', 'meta': {'msg': 'OK', 'status': 200}}
        try:
    
            # 加密分頁
            workorder = WorkOrderInfo.objects.all()
            # count = WorkOrderInfo.objects.count()
            pg = MyCursorPagination()
            page_query = pg.paginate_queryset(queryset=workorder, request=request, view=self)
            workorder_ser = WorkOrderSerializer(page_query, many=True)
            print(workorder_ser)
            # res = pg.get_paginated_response(workorder_ser)

            # result['data'] = workorder_ser.data
            # result['count'] = count

            # print(result)
        except Exception as e:
            result['meta']['msg'] = '獲取數據失敗'
            result['meta']['status'] = 500
        # 注:使用 get_paginated_response 方法才能返回上下頁的正確頁碼
        return pg.get_paginated_response(workorder_ser.data)

如下所示

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章