How do I include related model fields using Django Rest Framework?
The simplest way is to use the depth argument
class ClassroomSerializer(serializers.ModelSerializer):
class Meta:
model = Classroom
depth = 1
However, that will only include relationships for forward relationships, which in this case isn't quite what you need, since the teachers field is a reverse relationship.
If you've got more complex requirements (eg. include reverse relationships, nest some fields, but not others, or nest only a specific subset of fields) you can nest serializers, eg...
class TeacherSerializer(serializers.ModelSerializer):
class Meta:
model = Teacher
fields = ('id', 'name', 'tenure')
class ClassroomSerializer(serializers.ModelSerializer):
teachers = TeacherSerializer(source='teacher_set')
class Meta:
model = Classroom
Note that we use the source argument on the serializer field to specify the attribute to use as the source of the field. We could drop the source
argument by instead making sure the teachers
attribute exists by using the related_name option on your Teacher
model, ie. classroom = models.ForeignKey(Classroom, related_name='teachers')
One thing to keep in mind is that nested serializers do not currently support write operations. For writable representations, you should use regular flat representations, such as pk or hyperlinking.
Thank you @TomChristie!!! You helped me a lot! I would like to update that a little (because of a mistake I ran into)
class TeacherSerializer(serializers.ModelSerializer):
class Meta:
model = Teacher
fields = ('id', 'name', 'tenure')
class ClassroomSerializer(serializers.ModelSerializer):
teachers = TeacherSerializer(source='teacher_set', many=True)
class Meta:
model = Classroom
field = ("teachers",)