Django Rest Framework 全局分页和 pagination_class 不工作

Django Rest Framework global pagination and pagination_class are not working

我的设置:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 2
}

我的分页Class:

from rest_framework.pagination import PageNumberPagination


class CustomNumberPagination(PageNumberPagination):
    page_size = 5

我的测试视图Class:

from rest_framework.pagination import PageNumberPagination
from .pagination import CustomNumberPagination


class Testing(generics.GenericAPIView):

    queryset = Testing.objects.all()
    serializer_class = TestingSerializer
    pagination_class = CustomNumberPagination

    def get(self, request):
        print PageNumberPagination.page_size  # 2
        print self.pagination_class.page_size  # 5
        queryset = self.get_queryset()
        serializer = self.serializer_class(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

我可以在我的控制台中正确打印出 PageNumberPagination 和 CustomNumberPagination 的 page_size。

但是,将 page 作为参数传递没有任何效果。我无法在每个视图中使用全局分页或 pagination_class。我不确定哪里出了问题,但似乎大多数人都在做同样的事情,只是为他们工作。如果有任何建议,我将不胜感激。

更新

刚刚从我下面选择的答案中得到了一些启发。

因为我必须在覆盖的 get() 中写很多自定义项,所以我刚刚更新了我的 get()

from rest_framework.pagination import PageNumberPagination
from .pagination import CustomNumberPagination


class Testing(generics.GenericAPIView):

    queryset = Testing.objects.all()
    serializer_class = TestingSerializer
    pagination_class = CustomNumberPagination

    def get(self, request):
        queryset = self.get_queryset()
        page = self.request.query_params.get('page')
        if page is not None:
            paginate_queryset = self.paginate_queryset(queryset)
            serializer = self.serializer_class(paginate_queryset, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.serializer_class(queryset, many=True)
        return Response(serializer.data)

看看drf本身是怎么做的:

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

希望这对您有所帮助 - self-explanatory;

你使用了GenericAPIView - 并覆盖了get - 你应该使用get_paginated_response方法来实现分页。

编码愉快。