Django REST Framework - writeable nested serializers


DRF tip:

ModelSerializer's .create() method does not support writable nested fields by default.

For the nested serializer to be writable, you'll need to create create() and/or update() methods to explicitly specify how the child relationships should be saved.

👇

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ("title", "content")


class TagSerializer(serializers.ModelSerializer):
    posts = PostSerializer(many=True)

    class Meta:
        model = Tag
        fields = ['name', 'posts']

    def create(self, validated_data):
        posts_data = validated_data.pop('posts')
        tag = Tag.objects.create(**validated_data)

        for post in posts_data:
            Post.objects.create(tag=tag, **post)

        return tag