Post to nested fields with Django Rest Framework serializers
<p>I have setup my serializer to return nested content successfully.</p>

<p>However, I have not been able to post data within the nested fields.</p>

<p>I don't get an error when posting the data- but it only posts to the non-nested fields.</p>

<p>I would like for it to take the "name" field OR primary key (of model "TAG") for posting item.</p>

<p>Models.py</p>

<pre><code>class Tag(models.Model):
    name = models.CharField("Name", max_length=5000, blank=True)
    def __str__(self):
        return self.name

class Movie(models.Model):
    title = models.CharField("Whats happening?", max_length=100, blank=True)
    tag = models.ManyToManyField('Tag', blank=True)
    def __str__(self):
        return self.title
</code></pre>

<p>Serializers.py:</p>

<pre><code>class TagSerializer(serializers.ModelSerializer):
    taglevel = filters.CharFilter(taglevel="taglevel")
    class Meta:
        model = Tag
        fields = ('name', 'taglevel', 'id')

class MovieSerializer(serializers.ModelSerializer):
    tag = TagSerializer(many=True, read_only=False)
    info = InfoSerializer(many=True, read_only=True)
    class Meta:
        model = Movie
        fields = ('title', 'tag', 'info')

def validate(self, data):
    print(self.initial_data.__dict__)
    data['tag_name'] = []
    if 'tag' in self.initial_data.keys():
        for entry in self.initial_data['tag']:     
            data['tag_name'].append(entry['name'])
    return data

def create(self, validated_data):
    print(validated_data)
    tags_data = validated_data.pop('tag')
    movie = Task.objects.create(**validated_data)
    for tag_data in tags_data:
        Movie.objects.create(name=name, **tag_data)
    return movie
</code></pre>

<p>Sample of posting data:</p>

<pre><code>r = requests.post('http://localhost:8000/api/Data/',{ "title": "TEST_title", "tag": [ { "name": "test1", "name": "test2" } ], "info": [] })
</code></pre>

<p>Your json should be.</p>

<pre><code>{ 
"title": "TEST_title", 
"tag": [ {"name": "test1" },
        {"name": "test2"}
       ],
"info": []
}
</code></pre>

<hr>

<pre><code>class TagSerializer(serializers.ModelSerializer):
    taglevel = filters.CharFilter(taglevel="taglevel")

    class Meta:
        model = Tag
        fields = ('name', 'taglevel', 'id')


class MovieSerializer(serializers.ModelSerializer):
    tag = TagSerializer(many=True, read_only=False)
    info = InfoSerializer(many=True, read_only=True)

    class Meta:
        model = Movie
        fields = ('title', 'tag')

    def create(self, validated_data):
        tags_data = validated_data.pop('tag')
        movie = Movie.objects.create(**validated_data)
        for tag_data in tags_data:
            movie.tag.create(**tag_data)
        return movie
</code></pre>

python django django-rest-framework