Django Rest Framework:在ViewSet上打开分页(如ModelViewSet分页) [英] Django Rest Framework: turn on pagination on a ViewSet (like ModelViewSet pagination)

查看:1772
本文介绍了Django Rest Framework:在ViewSet上打开分页(如ModelViewSet分页)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的ViewSet来列出用户的数据:

I have a ViewSet like this one to list users' data:

class Foo(viewsets.ViewSet):

    def list(self, request):
        queryset = User.objects.all()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

我想打开分页,像ModelViewSet的默认分页:

I want to turn on pagination like the default pagination for ModelViewSet:

{
    "count": 55,
    "next": "http://myUrl/?page=2",
    "previous": null,
    "results": [{...},{...},...,{...}]
}

官方文档说:


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

Pagination is only performed automatically if you're using the generic views or viewsets

...但是我的结果集没有分页。如何分页?

...but my resultset is not paginated at all. How can I paginate it?

推荐答案


如果您使用通用
视图或视图

Pagination is only performed automatically if you're using the generic views or viewsets

第一个包版将文档翻译成英文。他们打算传达的是你想要一个通用的视图。通用视图集从通用ApiViews 中扩展,它们具有额外的分类方法查询和响应。

The first roadblock is translating the docs to english. What they intended to convey is that you desire a generic viewset. The generic viewsets extend from generic ApiViews which have extra class methods for paginating querysets and responses.

此外,您提供自己的列表方法,但默认分页过程实际上是由 mixin 处理:

Additionally, you're providing your own list method, but the default pagination process is actually handled by the mixin:

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)

使用框架代码:

class Foo(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer = UserSerializer

如果您需要更复杂的解决方案自定义列表方法,那么您应该按照您的看法编写,但以上述mixin代码段的风格。

The more complex solution would be if you need a custom list method, then you should write it as you see fit but in the style of the above mixin code snippet.

这篇关于Django Rest Framework:在ViewSet上打开分页(如ModelViewSet分页)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆