Prevent serializer creating duplicate items (update_or_create on Nested items)
<p>When I post via the API, I want the serializer not duplicated a tag if one exists with the same name.</p>

<p>I tried adding "unique" to the model field of "name" in the class Tag but this did not work- it wouldn't allow me to create other Movie's that linked to a tag which exists.</p>

<ul>
<li><p>Check if the field "name" already exists (case <strong>insensitive</strong>).</p></li>
<li><p>If  the tag "name" exists, just create the FK relationship with the
existing tag name &amp; the new movie</p></li>
<li><p>If the tag "name" doesn't exist, create it</p></li>
</ul>

<h1>Models.py</h1>

<pre><code>class Tag(models.Model):
    name = models.CharField("Name", max_length=5000, blank=True)
    taglevel = models.IntegerField("Tag level", 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>

<h1>Serializers.py</h1>

<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 get_or_create(self, validated_data):
    tags_data = validated_data.pop('tag')
    task = Task.objects.get_or_create(**validated_data)
    for tag_data in tags_data:
        task.tag.get_or_create(**tag_data)
    return task
</code></pre>

<p>The get_or_create doesn't work (trace here: <a href="http://dpaste.com/2G0HESS" rel="nofollow">http://dpaste.com/2G0HESS</a>) as it tells me AssertionError: The <code>.create()</code> method does not support writable nested fields by default.</p>

<p>You'll have to write custom create method for your models. <a href="http://www.django-rest-framework.org/topics/3.0-announcement/#writable-nested-serialization" rel="nofollow">Here is why.</a></p>

python django django-rest-framework