DRF 分页
Posted liwenzhou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DRF 分页相关的知识,希望对你有一定的参考价值。
rest framework中提供三种分页:
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
全局配置文件:
REST_FRAMEWORK = { ‘PAGE_SIZE‘: 2 }
1. 分页,看第n页,每页显示n条数据
例如:http://127.0.0.1:8000/api/article/?page=2&size=1
分页
class MyPageNumber(PageNumberPagination): page_size = 2 # 每页显示多少条 page_size_query_param = ‘size‘ # URL中每页显示条数的参数 page_query_param = ‘page‘ # URL中页码的参数 max_page_size = None # 最大页码数限制
视图
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分页 page_obj = MyPageNumber() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data return Response(res)
返回带页码链接的响应
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分页 page_obj = MyPageNumber() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data return page_obj.get_paginated_response(res)
2. 分页,在n个位置,向后查看n条数据
例如:http://127.0.0.1:8000/api/article/?offset=2&limit=2
分页
# offset分页 class MyLimitOffset(LimitOffsetPagination): default_limit = 1 limit_query_param = ‘limit‘ offset_query_param = ‘offset‘ max_limit = 999
视图
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分页 page_obj = MyLimitOffset() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data return page_obj.get_paginated_response(res)
3.加密分页,把上一页和下一页的id值记住
分页
# 加密分页 class MyCursorPagination(CursorPagination): cursor_query_param = ‘cursor‘ page_size = 1 ordering = ‘-id‘
视图
class ArticleList(APIView): def get(self, request, *args, **kwargs): res = {"code": 0} article_list = models.Article.objects.all().order_by("id") # 分页 page_obj = MyCursorPagination() page_article = page_obj.paginate_queryset(queryset=article_list, request=request, view=self) ser_obj = ArticleSerializer(page_article, many=True) res["data"] = ser_obj.data # return Response(res) return page_obj.get_paginated_response(res)
!--?xml>!--?xml>
以上是关于DRF 分页的主要内容,如果未能解决你的问题,请参考以下文章