[Django]-Django REST Framework: Flatten nested JSON to many objects

3👍

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!

Leave a comment