[Fixed]-"<Model> with this <field> already exist" on PUT call – Django REST Framework

20👍

Even through you’re doing an update, it doesn’t mean the nested data will just be updated.

You’re simply saying that you want to update the top most object.

In some cases, you’ll be removing or creating new nested objects while updating the top most one.

Therefore DRF considers by default that nested objects are for creation. You can work around this by explicitly removing the unique constraint on the nested serializer:

class AttributeChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = AttributeChoice
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': False},
            'slug': {'validators': []},
        }

2👍

Someone has already developed a handy UniqueFieldsMixin for solving the problem:

pip install drf-writable-nested

now:

from drf_writable_nested import UniqueFieldsMixin

class User(models.Model):
     name = models.CharField(max_length=200, unique=True)

class UserSerializer(UniqueFieldsMixin, serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

0👍

I think it is because of the validators.

Like:

Django rest serializer Breaks when data exists

As my solution, I mark this nested field to read_only=True,
And do my own update, create function to access self.initial_data to handle myself.

Leave a comment