有三类分页:
- 看第n页,每页显示多少数据,
PageNumberPagination - 在某个位置向后查看多少条数据,
LimitOffsetPagination - 加密分页,只能看上页和下页,会存储当前页的数据库记录的id最大值和id最小值,
CursorPagination
对其了解到如何使用就可以了。
PageNumberPagination使用
基本使用
1.settings.py文件中配置每页显示条数
REST_FRAMEWORK = {
'PAGE_SIZE': 2,
}
2.路由,显示角色的信息 re_path(r'^(?P<version>[v1|v2]+)/roles/pager/$', views.PagerView.as_view(), name='page') 3.视图函数,使用分页器
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import Response
class PagerView(APIView):
def get(self, request, *args, **kwargs):
roles = models.Role.objects.all()
pg = PageNumberPagination()
print(pg)
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
ser = RolesSerializers(instance=pager_roles, many=True)
return Response(ser.data)
4.测试 拿到第一页: 第二页数据
自定义分页
可以通过request中的参数来调整页面显示的条数和显示的页数。
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import Response
class MyPageNumberPagination(PageNumberPagination):
page_size = 3
page_query_param = "page"
page_size_query_param = 'size'
max_page_size = 6
class PagerView(APIView):
def get(self, request, *args, **kwargs):
roles = models.Role.objects.all()
pg = MyPageNumberPagination()
print(pg)
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
ser = RolesSerializers(instance=pager_roles, many=True)
return Response(ser.data)
get_pagirated_response方法
可以获取一个response,给前端返回这个方法的返回值
class PagerView(APIView):
def get(self, request, *args, **kwargs):
roles = models.Role.objects.all()
pg = MyPageNumberPagination()
print(pg)
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
ser = RolesSerializers(instance=pager_roles, many=True)
return pg.get_paginated_response(ser.data)
可以看到,前端拿到的返回值中有数据总条数,上一页的链接,下一页的链接。
LimitOffsetPagination
基本使用
和PageNumberPagination 一样,条数限制变成了limit(表示取多少条)和offset(表示从哪个位置开始)。
自定义分页
class MyLimitOffsetPagination(LimitOffsetPagination):
default_limit = 2
limit_query_param = 'limit'
offset_query_param = 'offset'
max_limit = 6
class PagerView(APIView):
def get(self, request, *args, **kwargs):
roles = models.Role.objects.all()
pg = MyLimitOffsetPagination()
print(pg)
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
ser = RolesSerializers(instance=pager_roles, many=True)
return pg.get_paginated_response(ser.data)
CursorPagination
自定义分页
class MyCursorPagination(CursorPagination):
cursor_query_param = 'cursor'
ordering = 'id'
page_size_query_param = 'size'
max_page_size = 6
class PagerView(APIView):
def get(self, request, *args, **kwargs):
roles = models.Role.objects.all()
pg = MyCursorPagination()
print(pg)
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
ser = RolesSerializers(instance=pager_roles, many=True)
return pg.get_paginated_response(ser.data)
可以观察到,cursor后是加密后的值。只能通过点击返回之中的链接来进行上下页的跳转。
|