在Django Rest框架viewset中为list方法设置分页

时间:2019-02-07 05:26:43

标签: python django pagination django-rest-framework

我有一个Viewset,该Viewset具有以下 list 方法:

class PolicyViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = Policy.objects.all()
        serializer = PolicySerializer(queryset, many=True)
        return Response(serializer.data)

这可以按预期工作,并且得到了我想要的响应。但是,现在我试图限制每个 GET 请求返回的对象,并且为此我使用了分页功能。 settings.py:

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

}

文档说:

  

只有在使用通用视图或视图集时,才会自动执行分页。

但是,我的结果仍未分页。启用分页还需要做些什么?

2 个答案:

答案 0 :(得分:2)

如果覆盖列表或任何主要方法,则需要为此显式调用。

class PolicyViewSet( viewsets.GenericViewset):
    def list(self, request):
        queryset = Policy.objects.all()
        page = self.paginate_queryset(queryset)
        serializer = PolicySerializer(page, many=True)
        return self.get_paginated_response(serializer.data)

答案 1 :(得分:0)

您可以使用 GenericViewSetModelViewSet(因为它也继承自 GenericViewSet)。

<块引用>

使用 GenericViewSetModelViewSet

# or class PolicyViewSet(viewsets.GenericViewSet):
class PolicyViewSet(viewsets.ModelViewSet):

    def list(self, request):
        queryset = Policy.objects.all()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = PolicySerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        else:
            serializer = PolicySerializer(queryset, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
<块引用>

使用 ViewSet

class PolicyViewSet(viewsets.ViewSet):

    def list(self, request):
        from rest_framework.pagination import PageNumberPagination
        queryset = Policy.objects.all()
        paginator = PageNumberPagination()
        page = paginator.paginate_queryset(queryset, request)
        if page is not None:
            serializer = PolicySerializer(page, many=True)
            return paginator.get_paginated_response(serializer.data)
        else:
            serializer = PolicySerializer(queryset, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)