rest_framework 分页
分页代码
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination class MyPagination(PageNumberPagination): # 分页 http://127.0.0.1:8000/pageview/?page=2 page_size = 1 max_page_size = 100 # page_size_query_param = 'size' page_query_param = 'page' class MyLimitPagination(LimitOffsetPagination): # http://127.0.0.1:8000/pageview2/?offset=1&limit=1 default_limit=2 limit_query_param = 'limit' offset_query_param = 'offset' max_limit = 100 class MyCursorPagination(CursorPagination): # 加密分页 http://127.0.0.1:8000/pageview2/?cursor=Ao23Jje8d2 cursor_query_param = 'cursor' ordering = '-id' page_size = 2 # page_size_query_param = 'size' max_page_size = 100
视图代码。 序列化代码相同,序列化实例instance参数值变化。
class PageView(APIView): def get(self, request, *args, **kwargs): roles=Role.objects.all() # ser=PageSerializer(instance=roles,many=True) # return json.dumps(ser.data) # return Response(ser.data) pg=MyPagination() pager_roles=pg.paginate_queryset(queryset=roles,request=request,view=self) ser=PageSerializer(instance=pager_roles,many=True) # return Response(ser.data) return pg.get_paginated_response(ser.data)