Django rest framework 分页

2020-01-09  本文已影响0人  Joncc

自定议分页类

from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination

class MyLimitOffsetPagination(LimitOffsetPagination):
    #默认显示的个数
    default_limit = 2
    #当前的位置
    offset_query_param = "offset"
    #通过limit改变默认显示的个数
    limit_query_param = "limit"
    #一页最多显示的个数
    max_limit = 100

视图:

from rest_framework.views import APIView, Response, Request
from rest_framework.versioning import URLPathVersioning
from myapp.db.serializers import *
from  myapp.common.page_number import  LimitOffsetPagination

class TestView(APIView):
    """
    test api
    """

    def get(self, request, *args, **kwargs):        
        testinfo = Operalog.objects.all()
        # 创建分页对象,这里是自定义的
        pg = LimitOffsetPagination()
        # 获取分页的数据
        page_roles = pg.paginate_queryset(queryset=testinfo, request=request, view=self)
        # 对数据进行序列化
        serialzer = OperalogSerializer(instance=page_roles, many=True)
        #  自带分页, get_paginated_response方法
        return pg.get_paginated_response(serialzer.data)

请求:


image.png

参考: https://www.cnblogs.com/derek1184405959/p/8727595.html

上一篇下一篇

猜你喜欢

热点阅读