V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ns2250225
V2EX  ›  Python

Django Rest Framework 怎样在 ModelViewSet 中既分页又能获取所有数据

  •  
  •   ns2250225 ·
    ns2250225 · 2018-12-10 10:47:03 +08:00 · 3117 次点击
    这是一个创建于 2177 天前的主题,其中的信息可能已经有所发展或是发生改变。
    RT,求大神指教,🙏
    2 条回复    2018-12-10 12:28:08 +08:00
    careofzm
        1
    careofzm  
       2018-12-10 12:05:44 +08:00   ❤️ 1
    你可以这样实现
    from django.shortcuts import render
    from django.contrib.auth.models import User
    import random
    from rest_framework.response import Response
    # Create your views here.
    b = [str(i) for i in range(10)]
    for i in range(10):
    a = random.sample(b, 5)
    User.objects.update_or_create(username=''.join(a))


    from rest_framework import serializers
    from rest_framework import pagination
    from rest_framework.viewsets import ModelViewSet
    from collections import OrderedDict, namedtuple


    class UserSerializer(serializers.ModelSerializer):
    class Meta:
    model = User
    fields = '__all__'


    class UserPagination(pagination.PageNumberPagination):
    page_size = 20

    def get_paginated_response(self, data):
    return Response(OrderedDict([
    ('count', self.page.paginator.count),
    ('next', self.get_next_link()),
    ('previous', self.get_previous_link()),
    ('page_size', self.page_size),
    ('results', data)
    ]))


    class UserViewset(ModelViewSet):
    serializer_class = UserSerializer
    pagination_class = UserPagination

    def get_queryset(self):
    return User.objects.all()

    def list(self, request, *args, **kwargs):

    status = request.query_params.get("status")
    users = self.get_queryset()
    if status == '1':
    self.paginator.page_size = users.count()

    page = self.paginate_queryset(users)
    serializer = self.get_serializer(page, many=True)
    return self.get_paginated_response(serializer.data)


    效果如下


    ns2250225
        2
    ns2250225  
    OP
       2018-12-10 12:28:08 +08:00 via Android
    @careofzm 感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5547 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 08:32 · PVG 16:32 · LAX 00:32 · JFK 03:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.