Ycon
Ycon

Reputation: 1950

Prevent serializer creating duplicate items (update_or_create on Nested items)

When I post via the API, I want the serializer not duplicated a tag if one exists with the same name.

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.

Models.py

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

Serializers.py

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

The get_or_create doesn't work (trace here: http://dpaste.com/2G0HESS) as it tells me AssertionError: The .create() method does not support writable nested fields by default.

Upvotes: 0

Views: 4901

Answers (1)

user6399774
user6399774

Reputation: 116

You'll have to write custom create method for your models. Here is an example.

Upvotes: 2

Related Questions