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

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

8 Comments

I know Pagination. But I want to add more object to count with conditions., Example, counts object with id >2
busy now,will update later.This should override get_paginated_response method
see update,it's untested code,if any error occur please tell me.
annotate can add a field to queryset but can not return the field to front.If you want be simple,just override list method to custom response.
keep asking,one day you will :)
|
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.

3 Comments

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
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
I am not sure about the error may be this will help stackoverflow.com/questions/21639275/…
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()

2 Comments

Could you elaborate ?
it will add 'count' field in response and give the total number of data in that model

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.