gpt4 book ai didi

python - 在 Django Rest Framework Viewset 中添加计数对象

转载 作者:行者123 更新时间:2023-12-02 06:37:24 25 4
gpt4 key购买 nike

我对在 Django Rest Framework View 集中添加计数对象有疑问:这是我当前的 API:

[
{
"id": 1,
"created": "2017-12-25T10:29:13.055000Z"
},
{
"id": 2,
"created": "2017-12-25T10:29:13.055000Z"
}
]

现在我想在此 API 外部添加 Count 对象,并将它们收集在 结果 数组中,如下所示:

{
"count_objects": 2,
"results": [
{
"id": 1,
"created": "2017-12-25T10:29:13.055000Z"
},
{
"id": 2,
"created": "2017-12-25T10:29:13.055000Z"
}
]
}

我怎样才能以正确的方式做到这一点?现在我的 viewset.py 是:

class NotificationAPIView(ReadOnlyModelViewSet):
queryset = Notification.objects.all()
serializer_class = NotificationSerializer

def get_queryset(self, *args, **kwargs):
queryset_list = Notification.objects.filter(to_user=self.request.user)
return queryset_list

最佳答案

设置.py

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100
}

你又来了,你真的应该阅读doc在询问之前。

更新:

from collections import OrderedDict
from rest_framework.response import Response

class Pagination(PageNumberPagination):
def paginate_queryset(self, queryset, request, view=None):
self.count_objects = queryset.filter(id__gt=2).count()
return super(Pagination, self).paginate_queryset(queryset, request, view=view)

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


class NotificationAPIView(ReadOnlyModelViewSet):
queryset = Notification.objects.all()
serializer_class = NotificationSerializer
pagination_class = Pagination

关于python - 在 Django Rest Framework Viewset 中添加计数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47973701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com