rest_framework学习之分页(Pagination)

DRF提供了默认的分页空间给开发者使用,只有在使用通用视图(generic views) 或视图集(viewsets)时才会自动触发分页控件,若使用的是APIView,需要自己实现分页API,可参考GenericAPIView源码

使用generic views来默认调用pagination

我们可以在settings.py中设置全局的分页控件配置,如下:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
}

设置完成后,我们在views中使用的generic和viewset,就会对使用list的方法默认做分页。

当然,我们也可以在视图中指定分页空间,新增如下分页类(需集成PageNumberPagination):

class CustomPagination(PageNumberPagination):
    page_size = 4
    page_size_query_param = 'page_size'
    max_page_size = 10000

在view中,使用方法如下:

from rest_framework.pagination import PageNumberPagination
from rest_framework.generics import ListAPIView

class CustomPagination(PageNumberPagination):
    page_size = 4
    page_size_query_param = 'page_size'
    max_page_size = 10000


class TestView(ListAPIView):
    queryset = ComModel.objects.all()
    serializer_class = ComSerializer
    pagination_class = CustomPagination

用APIView等视图使用分页控件

上述所说,如果使用APIView等若想要使用分页控件,需要自己调用分页API,我们编写测试代码如下:

from rest_framework.views import APIView
from core.models import ComModel
from core.api.serializers import ComSerializer
from rest_framework.pagination import PageNumberPagination


class CustomPagination(PageNumberPagination):
    page_size = 4
    page_size_query_param = 'page_size'
    max_page_size = 10000


class TestView(APIView):
    # queryset = ComModel.objects.all()
    # serializer_class = ComSerializer
    pagination_class = CustomPagination
    # authentication_classes = (BasicAuthentication, )
    # permission_classes = [IsAuthenticated]
    # parser_classes = (FormParser,)

    def get(self, request):
        queryset = ComModel.objects.all()
        print('++++++++++', queryset)
        print("=============", queryset[0].content)
        page = CustomPagination()
        instance = page .paginate_queryset(queryset)
        if instance is not None:
            serializer = ComSerializer(instance, many=True)
            return page .get_paginated_response(serializer.data)
        serializer = ComSerializer(queryset, many=True)
        return Response(serializer.data)

页面截图如下:
rest_framework学习之分页(Pagination)_第1张图片

你可能感兴趣的:(django)