I have this child model with parent field in it, and I'm getting a JSON from an API (which I can't control its format).
models.py:
class ChildModel(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
parent = models.CharField(max_length=100)
API.json:
{
"parent_name":'Homer',
"children":[
{
"name":'Bart',
"age":20
},
{
"name":'Lisa',
"age":15
},
{
"name":'Maggie',
"age":3
}
]
}
I'm trying to write a serializer that will get this JSON and will create 3 different child objects.
I manage to do this for one child:
class ChildSerializer(serializers.Serializer):
name = serializers.CharField()
age = serializers.IntegerField()
class ParentSerializer(serializers.ModelSerializer):
parent_name = serializers.CharField()
children = ChildSerializer(source='*')
class Meta:
model = ChildModel
fields = ('parent_name', 'children')
But when there are more than one child for a parent, I don't know how to save multiple children.
I tried to change it like this:
children = ChildSerializer(source='*', many=True)
But the validated data looks like this:
OrderedDict([(u'parent_name', u'Homer'), (u'name', u'age')])
Any suggestions how to make it possible?