0030 DRF框架开发(17 分页Pagination)

  DRF提供了分布支持

1 全局分页

  DRF全局分页,只需要在配置文件中按以下方式配置就可以了。不需要代码更改。

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS':  'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10  # 每页数目
}

2 自定义分页

  自定义分布主要是根据不同视图进行不同的分页处理。

  在GeneralTools下创建一个Paginations.py文件,专门用于该APP中所有用于自定义分页的类。

from rest_framework.pagination import PageNumberPagination


class SetPageSize5(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'


class SetPageSize10(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'


class SetPageSize15(PageNumberPagination):
    page_size = 15
    page_size_query_param = 'page_size'

  在视图中用pagination_class来引用上面自定义的类就可以了。代码如下:

from rest_framework import filters
from rest_framework.filters import OrderingFilter
from GeneralTools.Paginations import SetPageSize5


class SchoolViewSet(GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                    mixins.RetrieveModelMixin, mixins.DestroyModelMixin):
    queryset = Schools.objects.all()
    serializer_class = SchoolsSerializer
    filter_backends = [OrderingFilter, filters.SearchFilter]
    search_fields = ('name',)
    ordering_fields = ('teacher_quantity', 'student_quantity', 'employment_rate')
    pagination_class = SetPageSize5

3 在接口文档中找到SchoolViewSet接口的list方法,先测试全局分页,再测试自定义分页。效果如下:

猜你喜欢

转载自www.cnblogs.com/dorian/p/12383521.html