推荐学习书目
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 · Dec 10, 2018 · 3513 views
    This topic created in 2708 days ago, the information mentioned may be changed or developed.
    RT,求大神指教,🙏
    2 replies    2018-12-10 12:28:08 +08:00
    careofzm
        1
    careofzm  
       Dec 10, 2018   ❤️ 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
       Dec 10, 2018 via Android
    @careofzm 感谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1038 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 18:26 · PVG 02:26 · LAX 11:26 · JFK 14:26
    ♥ Do have faith in what you're doing.