Django Rest Framework,自定义page_size for list_route action

时间:2017-10-04 08:18:57

标签: django-rest-framework

我有一个list_route:

    @list_route(methods=['get'])
    def bought(self, request):
        bought_photos = Photo.objects.filter(is_bought=True)

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

如何仅为list_route设置自定义page_size,而不是为其ModelViewSet设置?

1)创建CustomPagination类

from rest_framework.pagination import PageNumberPagination

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

2)编辑list_route代码:

   @list_route(methods=['get'])
   def bought(self, request):
        bought_photos = Photo.objects.filter(is_bought=True)
        paginator = CustomPagination()

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

1 个答案:

答案 0 :(得分:1)

我认为以下代码应该足够了:

Selection