基本使用
(1)urls.py
urlpatterns = [
re_path('(?P[v1|v2]+)/page1/' , Pager1View.as_view(),) #分页1
]
(2)api/utils/serializers/pager.py
# api/utils/serializsers/pager.py
from rest_framework import serializers
from api import models
class PagerSerialiser(serializers.ModelSerializer):
class Meta:
model = models.Role
fields = "__all__"
(3)views.py
from api.utils.serializsers.pager import PagerSerialiser
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
class Pager1View(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象
pg = PageNumberPagination()
#获取分页的数据
page_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
#对数据进行序列化
ser = PagerSerialiser(instance=page_roles,many=True)
return Response(ser.data)
(4)settings配置
REST_FRAMEWORK = {
#分页
"PAGE_SIZE":2 #每页显示多少个
}
自定义分页类
#自定义分页类
class MyPageNumberPagination(PageNumberPagination):
#每页显示多少个
page_size = 3
#默认每页显示3个,可以通过传入pager1/?page=2&size=4,改变默认每页显示的个数
page_size_query_param = "size"
#最大页数不超过10
max_page_size = 10
#获取页码数的
page_query_param = "page"
class Pager1View(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象,这里是自定义的MyPageNumberPagination
pg = MyPageNumberPagination()
#获取分页的数据
page_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
#对数据进行序列化
ser = PagerSerialiser(instance=page_roles,many=True)
return Response(ser.data)
自定义
#自定义分页类2
class MyLimitOffsetPagination(LimitOffsetPagination):
#默认显示的个数
default_limit = 2
#当前的位置
offset_query_param = "offset"
#通过limit改变默认显示的个数
limit_query_param = "limit"
#一页最多显示的个数
max_limit = 10
class Pager1View(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象
pg = MyLimitOffsetPagination()
#获取分页的数据
page_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
#对数据进行序列化
ser = PagerSerialiser(instance=page_roles,many=True)
return Response(ser.data)
返回的时候可以用get_paginated_response方法
#自定义分页类3 (加密分页)
class MyCursorPagination(CursorPagination):
cursor_query_param = "cursor"
page_size = 2 #每页显示2个数据
ordering = 'id' #排序
page_size_query_param = None
max_page_size = None
class Pager1View(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象
pg = MyCursorPagination()
#获取分页的数据
page_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
#对数据进行序列化
ser = PagerSerialiser(instance=page_roles,many=True)
# return Response(ser.data)
return pg.get_paginated_response(ser.data)