from django.shortcuts import render,HttpResponse from rest_framework.pagination import PageNumberPagination from rest_framework.views import APIView from app01.models import Userinfo from utils.userinfo_ser import UserInfoSerializers import json # Create your views here. #分页类 #也可以使用全局配置 class CommonPageNumberPagination(PageNumberPagination): page_size = 5 # 每页显示的数据条数 page_query_param = 'page' # 页码的参数名 page_size_query_param = 'size' # 每页显示条数的参数名 max_page_size = 10 # 最大显示条数,只有size参数有值才会生效 #视图类 class Users(APIView): def get(self,request,*args,**kwargs): Userinfos = Userinfo.objects.all() ser = UserInfoSerializers(instance=Userinfos,many=True) pg = CommonPageNumberPagination() Users_data = pg.paginate_queryset(queryset=ser.data,request=request,view=self) #调用分页 data = json.dumps(Users_data,ensure_ascii=False) return HttpResponse(data)
还可以使用get_paginated_response方法(获取处理好的Response对象)。自带上一页和下一页
from django.shortcuts import render,HttpResponse from rest_framework.pagination import PageNumberPagination from rest_framework.views import APIView from app01.models import Userinfo from utils.userinfo_ser import UserInfoSerializers import json # Create your views here. #分页类 #也可以使用全局配置 class CommonPageNumberPagination(PageNumberPagination): page_size = 5 # 每页显示的数据条数 page_query_param = 'page' # 页码的参数名 page_size_query_param = 'size' # 每页显示条数的参数名 max_page_size = 10 # 最大显示条数,只有size参数有值才会生效 #视图类 class Users(APIView): def get(self,request,*args,**kwargs): Userinfos = Userinfo.objects.all() ser = UserInfoSerializers(instance=Userinfos,many=True) pg = CommonPageNumberPagination() Users_data = pg.paginate_queryset(queryset=ser.data,request=request,view=self) #调用分页 return pg.get_paginated_response(Users_data)
LimitOffsetPagination类
偏移分页,根据偏移量和限制条控制返回的数据。
即从第3条数据开始,取5条数据,http://127.0.0.1:8000/books/?limit=3&offset=5
继承LimitOffsetPagination重写属性:
class CommonLimitOffsetPagination(LimitOffsetPagination): default_limit = 5 # 每页默认显示多少条 limit_query_param = 'limit' # 限制条数的参数名 offset_query_param = 'offset' # 偏移量的参数名 max_limit = 6 # 最大限制条数
CursorPagination类
游标分页,根据当前游标位置控制返回的数据,页面跳转只能跳上一页和下一页,但是针对于大数据量分页效率高。
继承CursorPagination类重写属性:
class CommonCursorPagination(CursorPagination): cursor_query_param = 'cursor' # 游标的参数 page_size = 5 # 每页显示的条数 ordering = 'price' # 排序的字段,必须是表中有的字段
标签:分页,--,条数,query,import,drf,data,page,size From: https://www.cnblogs.com/powfu/p/16940119.html