DRF全局配置和列表分页器

1.offset分页

编辑LehuXuexi目录下的settings.py新增

REST_FRAMEWORK = {
     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
     'PAGE_SIZE': 10
}

再把[:10]10条限制去掉,发现页面有了分页功能,传入参数offset

2.page分页

修改REST_FRAMEWORK配置项

REST_FRAMEWORK = {
     #'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
     'PAGE_SIZE': 10
}

传入参数为page

3.自定义分页

如果使用settings.py配好的分页器,会对全局生效灵活性不高,使用自定义分页比较好,注释全局分页器,编辑blogs目录下的views.py

from rest_framework import generics
from rest_framework.pagination import PageNumberPagination

from .serializers import ArticleSerializer
from .models import Article

class StandardResultsSetPagination(PageNumberPagination):
    page_query_param = 'page'
    page_size = 15
    page_size_query_param = 'page_size'
    max_page_size = 1000

class ArticleListView(generics.ListCreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = StandardResultsSetPagination

一页展示15篇文章,最大限制是1000页,分页传入字段名为page

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://example.com/article/global-drf/