Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework: Flatten nested JSON to many objects

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?

like image 917
user1557330 Avatar asked Sep 26 '26 05:09

user1557330


1 Answers

You need to customize your serializer so that it creates all the children. For that, create() method is used.

Try this:

class ParentSerializer(serializers.Serializer):
    parent_name = serializers.CharField()
    children = ChildSerializer(many=True)

    def create(self, validated_data):
        parent_name = validated_data['parent']

        # Create or update each childe instance
        for child in validated_data['children']:
            child = Child(name=child['name'], age=child['age'], parent=valid, parent=parent_name)
            child.save()

        return child

The problem is that you don't have a Parent model. That's why I don't know what to return in the create() method. Depending on your case, change that return child line.

Hope it helps!

like image 118
Jahongir Rahmonov Avatar answered Sep 27 '26 19:09

Jahongir Rahmonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!