ModelSerializer uniqueness validation does not work for partial unique constraints #9411
Unanswered
elliot-wilson
asked this question in
Potential Issue
Replies: 2 comments
-
|
As a quick workaround, I was able to do: class PersonSerializer(serializers.ModelSerializer):
provider = serializers.CharField(validators=[])
class Meta:
model = Person
fields = "__all__"
def validate(self, data):
name = data.get("name")
is_active = data.get("is_active")
instance = self.instance
if is_active:
if Person.objects.filter(name=name, is_active=True).exclude(id=instance.id).exists():
raise serializers.ValidationError({"name": "There is already an active person with this name."})
return databut it seems a little hacky to be reimplementing the constraint in the serializer when it already exists on the model. I'd love to know what people think! |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
I'm experiencing the same issue. Has this been confirmed and will (potentially) get fixed or not? Thanks |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a model with a relatively common partial uniqueness constraint pattern: there can be many
Personinstances with a duplicatenamevalue, as long as only one of themis_active: True.However, when using a
ModelSerializerto validate data for that model, the uniqueness validation returnsFalsefor otherwise valid data if there is already aPersonwith thatnamein the database, even if the data hasis_active: False.Here's a dummy example:
The relevant source code is here:
django-rest-framework/rest_framework/utils/field_mapping.py
Lines 65 to 85 in 36d5c0e
and
django-rest-framework/rest_framework/validators.py
Lines 63 to 74 in 36d5c0e
Basically, the code is asking, "Is there already an
is_active: TruePersonwith thisname?", but I believe the correct question should be more like "Is there already a record in the database that matches the constraint condition AND does the current instance match the condition?"Beta Was this translation helpful? Give feedback.
All reactions