Extending serializers
You have learned how to serialize your model objects; however, often, you may want to enrich the response with additional relevant data or calculated fields. Let’s take a look at some of the options to extend serializers.
Adding additional fields to serializers
Let’s edit the subject views to include the number of courses available for each subject. You will use the Django aggregation functions to annotate the count of related courses for each subject.
Edit the api/views.py
file of the courses
application and add the following code highlighted in bold:
from django.db.models import Count
# ...
class SubjectListView(generics.ListAPIView):
queryset = Subject.objects.annotate(total_courses=Count('courses'))
serializer_class = SubjectSerializer
class SubjectDetailView(generics.RetrieveAPIView):
queryset = Subject.objects.annotate(total_courses=Count('courses'))
serializer_class = SubjectSerializer
...