drf-分页

一、三种分页模式

1 PageNumberPagination

from  rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination

class Mypagination(PageNumberPagination):
    page_size = 3  # 每页条数
    page_query_param = 'aaa'  # 查询第几页的key
    page_size_query_param = 'size'
    # 每一页显示的条数,可以在url后面拼接size=4,修改每页展示条数,但是这个条数不能超过最大展示数
    max_page_size = 5 # 每页最大展示数

class BookTest(ListAPIView):
    queryset = models.Book.objects.all()
    serializer_class = sers.Bookserializers
    pagination_class = Mypagination
    
# http://127.0.0.1:8000/api/books/?aaa=2&size=6

2 LimitOffsetPagination

class Mypagination(LimitOffsetPagination):
    default_limit = 3   # 每页条数
    limit_query_param = 'limit' # 往后拿几条的key
    offset_query_param = 'offset' # 标杆的key
    max_limit = 5   # 每页最大几条
# http://127.0.0.1:8000/api/books/?limit=3&offset=3

3 CursorPagination

class Mypagination(CursorPagination):
    cursor_query_param = 'cursor'  # 每一页查询的key
    page_size = 2  # 每页显示的条数
    ordering = '-id'  # 排序字段
# http://127.0.0.1:8000/api/books/?cursor=cj0xJnA9NQ%3D%3D

总结:在分页的时候我们通常是在查询全部的时候才需要分页,所以视图类必须继承ListAPIView或者继承规则与其相同也行。三种分页方式各有各的好处,第一种分页和第二种分页都是会把数据整体都拿出来,比较占资源,但是可以指定快速找到要找的数据。第三种分页方式就只能往前和往后,读取数据虽然很快,但是找到具体的数据就很慢

二、继承APIView的视图类下写分页

# 如果使用APIView分页
from utils.throttling import MyThrottle
class BookView(APIView):
    # throttle_classes = [MyThrottle,]
    def get(self,request,*args,**kwargs):
        book_list=models.Book.objects.all()
        # 实例化得到一个分页器对象
        page_cursor=MyPageNumberPagination()

        book_list=page_cursor.paginate_queryset(book_list,request,view=self)
        next_url =page_cursor.get_next_link()
        pr_url=page_cursor.get_previous_link()
        # print(next_url)
        # print(pr_url)
        book_ser=BookModelSerializer(book_list,many=True)
        return Response(data=book_ser.data)
posted @ 2020-07-13 19:41  lxttt521  阅读(10)  评论(0编辑  收藏