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,074 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,880 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,880 points
10,714 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,880 points
9,104 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,880 points
5,307 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,880 points
5,799 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,880 points
11,105 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,880 points
2,789 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