How to add annotate data in django-rest-framework queryset responses

0 votes

I am generating aggregates for each item in a QuerySet:

def get_queryset(self):
    from django.db.models import Count
    queryset = Book.objects.annotate(Count('authors'))
    return queryset

But I am not getting the count in the JSON response.

thank you in advance

Jun 25, 2020 in Python by kartik
• 37,520 points
6,129 views

1 answer to this question.

0 votes

Hello @kartik,

The queryset returned from get_queryset provides the list of things that will go through the serializer, which controls how the objects will be represented. Try adding an additional field in your Book serializer, like:

author_count = serializers.IntegerField(
    source='author_set.count', 
    read_only=True
)

Hope this helps!!

answered Jun 25, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How to disable a method in a ViewSet, django-rest-framework

Hello @kartik, You could keep using viewsets.ModelViewSet and define http_method_names on your ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,840 points
10,856 views
0 votes
1 answer

How to update user password in Django Rest Framework?

Hello @kartik, Using a modelserializer might be an ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,840 points
9,245 views
0 votes
1 answer

How can modify request.data in django REST framework?

Hello @kartik, Generally request in drf views is rest_framework.request.Request instance. Following to ...READ MORE

answered Jul 2, 2020 in Python by Niroj
• 82,840 points
5,443 views
0 votes
1 answer

How to order_by a JSON from serializers.py file in django rest framework?

Hello @kartik, There's an easy way, just override ...READ MORE

answered Jul 2, 2020 in Python by Niroj
• 82,840 points
5,873 views
0 votes
1 answer

How to return custom JSON in Django REST Framework?

Hello @kartik, There are 2 ways to custom ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,840 points
11,164 views
0 votes
1 answer

How to secure APIs for Registration and Login in Django Rest Framework?

Hello @kartik, you cannot have an authentication system ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,840 points
2,883 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP