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

2018-12-10 10:47:03 +08:00
 ns2250225
RT,求大神指教,🙏
3144 次点击
所在节点    Python
2 条回复
careofzm
2018-12-10 12:05:44 +08:00
你可以这样实现
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
2018-12-10 12:28:08 +08:00
@careofzm 感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/516032

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX