简体   繁体   中英

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM