Django休息框架:如何在ModelViewSet中关闭/打开分页

Dan*_*kov 5 csv django pagination django-rest-framework

我正在使用Django REST框架djangorestframework-csv以及默认的分页设置,但是当请求的格式为"CSV"时,就没有必要使用paginaion.可以禁用分页:

pagination_class = None

有可能动态地改变它吗?

class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"
Run Code Online (Sandbox Code Playgroud)

谢谢.

Mei*_*tro 11

一种选择是通过设置no_page查询参数来动态禁用视图上的分页:

def paginate_queryset(self, queryset, request, view=None):
    if 'no_page' in request.query_params:
        return None

    return super().paginate_queryset(queryset, request, view)
Run Code Online (Sandbox Code Playgroud)


Ykh*_*Ykh 5

如果您只想动态打开或关闭客户端的分页,您可以自定义分页类为:

class Pagination(PageNumberPagination):
    page_size_query_param = 'page_size'
    max_page_size = 100

    def get_page_size(self, request):
        if self.page_size_query_param:
            page_size = min(int(request.query_params.get(self.page_size_query_param, self.page_size)),
                        self.max_page_size)
            if page_size > 0:
                return page_size
            elif page_size == 0:
                return None
            else:
                pass
        return self.page_size
Run Code Online (Sandbox Code Playgroud)

使用此类作为您的 pagination_class,您可以通过请求 url " http://www.example.com/some_object/?page_size=0 "关闭分页, ?page_size=0 将禁用分页。如果您只想在请求格式为 CVS 时禁用分页,您可以尝试 danilke 所说的。


mif*_*har 5

这个解决方案对我有用

DRF 版本:3.11.0

Django 版本:2.2.7

默认情况下分页正在工作,但是当我传递查询参数“no_page”时,分页将被禁用:例如:http://localhost:8000/api/city/?no_page

class CityListView(generics.ListCreateAPIView):
    serializer_class = serializers.CitySerializer
    def paginate_queryset(self, queryset, view=None):
        if 'no_page' in self.request.query_params:
            return None
        else:
            return self.paginator.paginate_queryset(queryset, self.request, view=self)
Run Code Online (Sandbox Code Playgroud)