Unique constraint prevents nested serializers from updating · Issue #2996 · encode/django-rest-framework (original) (raw)
If you have a nested serializer which model does have a unique constraint on a field you're not able to reference an existing instance.
class Task(serializers.ModelSerializer):
class Meta:
model = models.Task
fields = ('id', 'name')
class Category(serializers.ModelSerializer):
tasks = Task(many=True)
class Meta:
model = models.Category
fields = ('id', 'name', 'tasks')
Let's say I created a category & task which I'm updating with the very same data they already have:
c = Category(data={"id": 1, "name": "Django", "tasks": [{"id": 1, "name": "Demo", "owner": "admin"}]})
c.is_valid() # Returns False
c.errors # Returns {'tasks': [{'name': ['This field must be unique.']}]}
The point is, name
remains unique because it matches its own id