以下内容为原创,转载请注明出处!

今天在Django restful api中遇到一个问题,后端用到pagination_class,用来实现分页,但是我想在api调用过程知道一共有多少页。

直接看代码:

from rest_framework.pagination import PageNumberPagination
from django.core.paginator import InvalidPage
from rest_framework.exceptions import NotFound
from django.utils import six
class StandardResultsSetPagination(PageNumberPagination):
        page_size = 10
        page_size_query_param = 'page_size'
        max_page_size = 100
        def paginate_queryset(self, queryset, request, view=None):
        """
        Paginate a queryset if required, either returning a
        page object, or `None` if pagination is not configured for this view.
        """
        page_size = self.get_page_size(request)
        if not page_size:
            return None
        paginator = self.django_paginator_class(queryset, page_size)
        page_number = request.query_params.get(self.page_query_param, 1)
        if page_number in self.last_page_strings:
            page_number = paginator.num_pages
        try:
            self.page = paginator.page(page_number)
        except InvalidPage as exc:
            msg = self.invalid_page_message.format(
                page_number=page_number, message=six.text_type(exc)
            )
            raise NotFound(msg)
        if paginator.num_pages > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True
        self.request = request
        return list(self.page), paginator.num_pages
class WorkOrderAPI(generics.GenericAPIView):
    serializer_class = WorkOrderSerializer
    queryset = WorkOrder.objects.all()
    pagination_class = StandardResultsSetPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_fields = ('status',)
    search_fields = ('orderid',)
    def get(self, request, format=None):
        work_order_status = request.GET.get('status','')
        if work_order_status == '5':
            query = self.queryset.filter(assessor=request.user.account.name)
            # rest_framework.pagination里面paginate_queryset返回的只有分页后的对象,我这里为什么能返回最大页码呢,查看源代码之后,重写paginate_queryset。自己返回即可
            page_list, num_pages = self.paginate_queryset(query)
        else:
            query = self.get_queryset()
            page_list, num_pages = self.paginate_queryset(self.filter_queryset(query))
        serializer = self.serializer_class((page_list), many=True)
        json_data = {}
        json_data["data"] = serializer.data
        json_data["num_pages"] = num_pages
        return Response(json_data, status=status.HTTP_200_OK)


效果如下: