如何让自定义分页类为django rest framework v3.6工作

时间:2017-07-30 14:08:37

标签: django rest pagination django-rest-framework

我试图按照the docs在ViewSet上实现自定义分页类,但分页设置只是不做任何事情。这是我的ViewSet的代码。

from rest_framework import status, permissions, viewsets
from rest_framework.pagination import PageNumberPagination

class ProductViewSetPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'
    max_page_size = 1000

class ProductViewSet(viewsets.ModelViewSet):

    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = ProductSerializer
    pagination_class = ProductViewSetPagination
    # ...

    def list(self, request):
        #get_queryset is also overridden to accept filters in query_params
        queryset = self.get_queryset()
        if not queryset.exists():
            return Response(status=status.HTTP_204_NO_CONTENT)

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

我甚至在settings.py文件中添加了一些默认值,但我仍然在product-list视图的单个页面上获取所有产品实例。我尝试将pagepage_size个查询参数添加到网址中;这并没有改变任何事情。

'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,

我错过了什么?

1 个答案:

答案 0 :(得分:2)

在超级列表中添加了分页,请尝试:

\config\app.php