Assume that, we implement a simple API and we have the following models.
class Parent(models.Model):
name = models.CharField(max_length=50)
class Child(models.Model):
parent = models.ForeignKey(Parent)
child_name = models.CharField(max_length=80)
And we want to return a response when a particular parent
is retrieved via API.
{
'url': 'https://dummyapidomain.com/parents/1/',
'id': '1',
'name': 'Dummy Parent Name',
'children': [{
'id': 1,
'child_name': 'Dummy Children I'
},
{
'id': 2,
'child_name': 'Dummy Children II'
},
{
'id': 3,
'child_name': 'Dummy Children III'
},
...
],
}
For this purpose, we implement the corresponding serializers like this:
class ChildSerializer(serializers.HyperlinkedModelSerializer):
parent_id = serializers.PrimaryKeyRelatedField(queryset=Parent.objects.all(),source='parent.id')
class Meta:
model = Child
fields = ('url','id','child_name','parent_id')
def create(self, validated_data):
subject = Child.objects.create(parent=validated_data['parent']['id'], child_name=validated_data['child_name'])
return child
class ParentSerializer(serializers.HyperlinkedModelSerializer):
children = ChildSerializer(many=True, read_only=True)
class Meta:
model = Course
fields = ('url','id','name','children')
To make this implementation work properly we need to update our Child
model and add a related_name to parent
field. Updated version of our Child
model implementation should be like this:
class Child(models.Model):
parent = models.ForeignKey(Parent, related_name='children') # <--- Add related_name here
child_name = models.CharField(max_length=80)
By doing this, we'll be able to get the list of all related children objects in parent's serializer.