9.分页操作
- 分页,看第n页,每页显示n条数据
- 分页,在n个位置,向后查看n条数据.
- 加密分页,上一页和下一页
1.基于PageNumberPagination分页
1.路由:
url(r'^(?P[v1|v2]+)/splitpage/$', views.SplitpageView.as_view(),),
2.视图函数
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
#分页需要导入类
class SplitpageView(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象
pg = PageNumberPagination()
#在数据库中获取分页的数据
pager_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
print(pager_roles)
#对数据进行序列化
ser = PagerSerialiser(instance=pager_roles,many=True)
return Response(ser.data)
#settings.py配置
REST_FRAMEWORK = {
"PAGE_SIZE":2,
}
- 返回效果:
- 自定义分页:
class MyPageNumberPagination(PageNumberPagination):
#一页显示数量
page_size = 2
#设置
page_size_query_param = "size"
#每页最大数量
max_page_size = 5
#url页数变量设置:
page_query_param = "page"
class SplitpageView(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象
pg = PageNumberPagination()
#在数据库中获取分页的数据
pager_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
print(pager_roles)
#对数据进行序列化
ser = PagerSerialiser(instance=pager_roles,many=True)
return Response(ser.data)
- 显示效果:
2.基于LimitOffsetPagination实现分页
class MyPageNumberPagination2(LimitOffsetPagination):
default_limit = 2
limit_query_param = "limit"
offset_query_param = "offset"
max_limit = 5
class SplitpageView(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象
pg = MyPageNumberPagination2()
#在数据库中获取分页的数据
pager_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
print(pager_roles)
#对数据进行序列化
ser = PagerSerialiser(instance=pager_roles,many=True)
return Response(ser.data)
- 显示结果
3.基于CursorPagination 分页(加密)
from rest_framework.pagination import CursorPagination
class MyPageNumberPagination3(CursorPagination):
#
cursor_query_param = "cursor"
page_size = 2
ordering = 'id'
page_size_query_param = None
max_page_size = None
class SplitpageView(APIView):
def get(self,request,*args,**kwargs):
#获取所有数据
roles = models.Role.objects.all()
#创建分页对象
pg = MyPageNumberPagination3()
#在数据库中获取分页的数据
pager_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
print(pager_roles)
#对数据进行序列化
ser = PagerSerialiser(instance=pager_roles,many=True)
return pg.get_paginated_response(ser.data)
4.总结:
#如果数据量大,如何做分页.
数据库性能相关?