You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Unique constraint prevents nested serializers from updating #2996
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
Reacted by Jeans K. Real, Rahul, Ángel Jiménez, Damir Abdullin, elonzh, Kourosh, Paul Johnson, Fabio, ratnesh-fc, Kedar and 4 more
I'm a bit uncomfortable with this.
Let's way our nested resource is either created or fetched from the DB ala get_or_create.
If we remove the validation, it may run in later issues.
If we keep it, it'll be impossible to get an item that already exists without changing it.
We don't support (automatic) writable nested serialization, so it's not totally unreasonable to also say 'validators' are not appropraite for this case, here's what you'd need to do. However if there's an alternative that'd def be worth considering.
So what is the way out? This to me seems like a major limitation.
Writing custom non-model serializer. - Almost all my endpoints would have custom serializers then.
Ignoring 'id' from 'to_internal_value' method.* - Might run into trouble later on because of this.
Any way to use model serializer but change the validation rule for nested serializr? some sort of mixin.. This would be an ideal way, not sure how to do it.
The workaround this is to remove the unique constraint from the serializer and move it to the business logic validation part since the nested serializer can not say - as of today - whether he's updating or creating a new object.
Reacted by Joe di Stefano, Gunther Cox, Nikolay Kiryanov and Nadia Neyla
The workaround this is to remove the unique constraint from the serializer and move it to the business logic validation part since the nested serializer can not say - as of today - whether he's updating or creating a new object.
I recently came across this issue (a user object attached to an account object via an intermediary relationship).
Within the context of the account, I wanted to be able to update both the user details and the relationship details as a single endpoint. The problem being that the email field on the user model is unique and fell foul of the issue described here.
I wasn't happy with breaking some very necessary validation, so I took a more direct approach. At the point of serializer initialisation, if the email supplied in the data is already the same as the email on the user, I simply removed it from the data. No change = no validation required*.
Okay, technically you could change the email validator and require user's with no-longer-valid emails to change them, but that seems a remote possibility in the extreme.
I don't kwon if there is a documentation for this now, but i recently fix this problem with a basic zero validators on the field that cause the problem.
I took a lot of time discovering this , so I hope some one else help it youruniquefield = serializers.CharField(max_length=255, min_length=4, validators=[])
Before this I always raise a already exist error even if I correct the problem with managers to use ger_or_create.
Wow DRF , you guys should wake up
It is 2022 and still the bug is not YET fixed all we find are irrelevant workarounds
Its a pity
and a bad pity at THAT
DRF WAKE UP and update your repo
Reacted by Daniil Selivanov, fbosso, Roman Maior and aeon
Reacted by Alex Scott, Rob Carleski, João Sousa, Kedar, DayDotMe and Julien Palard
@auvipy , I have used the package suggested (drf-writable-nested). It is actually so helpful. nothing to worry about updating multiple models through nested serializer.
Reacted by Asif Saif Uddin {"Auvi":"অভি"} and Roman Maior
Activity
lovelydinosaur commentedon Jun 2, 2015
It may be that we simply have to document this as a limitation in
validators.There's not really going to be any nice automatic ways to handle this.
xordoquy commentedon Jun 2, 2015
I'm a bit uncomfortable with this.
Let's way our nested resource is either created or fetched from the DB ala
get_or_create.If we remove the validation, it may run in later issues.
If we keep it, it'll be impossible to get an item that already exists without changing it.
lovelydinosaur commentedon Jun 2, 2015
We don't support (automatic) writable nested serialization, so it's not totally unreasonable to also say 'validators' are not appropraite for this case, here's what you'd need to do. However if there's an alternative that'd def be worth considering.
arw180 commentedon Aug 20, 2015
This sounds very similar to the issue I ran into today: http://stackoverflow.com/questions/32123148/writable-nested-serializer-with-existing-objects-using-django-rest-framework-3-2
xordoquy commentedon Aug 20, 2015
@arw180 indeed. Thanks for pointing to this issue, totally forgot about it.
Adding a reference to #3312 since it's the same.
irongomme commentedon Oct 4, 2015
Arrgh, i've search for a day why was it not works!!!
This is a really confusing issue, because it is a common thing to play with nested models, and i don't know how to get around of this problem ...
I've got this :
And i must save a contact with an account, they are inseparable. How can i do this without this annoying unique validator message ?
xordoquy commentedon Oct 5, 2015
The discussion group is the best place to take this discussion and other usage questions. Thanks!
ankitml commentedon Oct 26, 2015
So what is the way out? This to me seems like a major limitation.
xordoquy commentedon Oct 26, 2015
The workaround this is to remove the unique constraint from the serializer and move it to the business logic validation part since the nested serializer can not say - as of today - whether he's updating or creating a new object.
7 remaining items
xordoquy commentedon Dec 26, 2016
ColinBarnwell commentedon Jan 27, 2017
I recently came across this issue (a user object attached to an account object via an intermediary relationship).
Within the context of the account, I wanted to be able to update both the user details and the relationship details as a single endpoint. The problem being that the email field on the user model is unique and fell foul of the issue described here.
I wasn't happy with breaking some very necessary validation, so I took a more direct approach. At the point of serializer initialisation, if the email supplied in the data is already the same as the email on the user, I simply removed it from the data. No change = no validation required*.
Ostlander commentedon Feb 5, 2017
@xordoquy, would that work?
xordoquy commentedon Feb 5, 2017
The discussion group is the best place to take further this discussion and other usage questions. Thanks!
xtornasol512 commentedon Apr 25, 2017
I don't kwon if there is a documentation for this now, but i recently fix this problem with a basic zero validators on the field that cause the problem.
I took a lot of time discovering this , so I hope some one else help it
youruniquefield = serializers.CharField(max_length=255, min_length=4, validators=[])Before this I always raise a already exist error even if I correct the problem with managers to use ger_or_create.
xordoquy commentedon Apr 25, 2017
I wrote some time ago an article about that if that helps: https://medium.com/django-rest-framework/dealing-with-unique-constraints-in-nested-serializers-dade33b831d9
Cleanup of PlanItLocation additions
Break PlanItLocation out from org model
m-ali-94 commentedon Jan 8, 2020
there is this 3rd party library https://github.com/beda-software/drf-writable-nested, it has a UniqueFieldsMixin which can do the magic to handle unique constraints.
studioj commentedon Jan 31, 2021
for those ending up here => this SO answer helps
https://stackoverflow.com/a/32452603/2559785
iamunadike commentedon Aug 5, 2022
Wow DRF , you guys should wake up
It is 2022 and still the bug is not YET fixed all we find are irrelevant workarounds
Its a pity
and a bad pity at THAT
DRF WAKE UP and update your repo
mirodil1 commentedon Nov 6, 2023
Same problem here. Has it fixed yet ?
auvipy commentedon Nov 6, 2023
you might try this and report back?
basheeromy commentedon Dec 18, 2023
@auvipy , I have used the package suggested (drf-writable-nested). It is actually so helpful. nothing to worry about updating multiple models through nested serializer.
psgpyc commentedon Sep 16, 2024
Has this been fixed yet? I tried doing the same thing today and the issue persists. I am using PrimaryKeyRelatedField as a workaround.