2

I have a question with adding Count Objects in Django Rest Framework Viewset: This is my curren API:

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

Now I want to add Count Objects outside this API and collect them in results array like this:

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

How can I do this in the right way? Now my viewset.py is:

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
KitKit
  • 8,549
  • 12
  • 56
  • 82

3 Answers3

4

settings.py

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

You again,you really should read doc before ask.

Update:

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
Ykh
  • 7,567
  • 1
  • 22
  • 31
1

This will filter the values and add a count for the field status in the result.

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

For detail see documentation

Hope this helps.

Tony Roczz
  • 2,366
  • 6
  • 32
  • 59
  • You put it as separate function and call the function or in your existing `queryset_list = Notification.objects.filter(to_user=self.request.user).values('to_user').annotate(count=Count('to_user'))` since the to_user will be common in all the rows use that – Tony Roczz Dec 26 '17 at 05:05
  • `SyntaxError: Non-ASCII character '\xe2' in file views.py on line 20, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details` This error is created – KitKit Dec 26 '17 at 05:12
  • I am not sure about the error may be this will help https://stackoverflow.com/questions/21639275/python-syntaxerror-non-ascii-character-xe2-in-file – Tony Roczz Dec 26 '17 at 06:39
1

serializers.py

class YourSerializer(serializers.ModelSerializer)

    count = serializers.SerializerMethodField('get_count')
    class Meta:
         model = YourModel
         fields = ['...., count']

    def get_count(self, obj):    
        return YourModel.objects.all().count()