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

时间:2017-12-26 03:48:50

标签: python django django-rest-framework

我有一个在Django Rest Framework Viewset中添加计数对象的问题: 这是我当前的API:

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

现在我想在此API之外添加计数对象,并将其收集在结果数组中,如下所示:

{
    "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

2 个答案:

答案 0 :(得分:2)

settings.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

答案 1 :(得分:1)

这将过滤值并在结果中添加字段status的计数。

def count:
    Model.objects.filter(value=value).values('status').annotate(count=Count('status'))

详细信息see documentation

希望这有帮助。