Creating nested serializers
If we want to include more information about each module, we need to serialize Module
objects and nest them. Modify the previous code of the api/serializers.py
file of the courses
application to make it look as follows:
from django.db.models import Count
from rest_framework import serializers
from courses.models import Course, Module, Subject
class ModuleSerializer(serializers.ModelSerializer):
class Meta:
model = Module
fields = ['order', 'title', 'description']
class CourseSerializer(serializers.ModelSerializer):
modules = ModuleSerializer(many=True, read_only=True)
class Meta:
# ...
In the new code, you define ModuleSerializer
to provide serialization for the Module
model. Then, you modify the modules
attribute of CourseSerializer
to nest the ModuleSerializer
serializer. You keep many=True
to indicate that you are serializing multiple objects and read_only=True
to keep this field...