Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

UniqueConstraint violation_error_message as error response in drf#9352

Unanswered
AGM-90 asked this question inGeneral
Discussion options

Example Model
class UniqueTest(BaseModel):
answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
date = models.DateField()

class Meta:    constraints = [        models.UniqueConstraint(            fields=["answer", "subject","date"],            condition=Q(deleted_at=None),            name="uniq_if_not_del_pjt_site_sub_mil",            violation_error_message="test error message"        )    ]

Sample error response for violation
{
"non_field_errors": [
"The fields answer, subject, date must make a unique set."
]
}
Expected error response
{
"non_field_errors": [
"test error message"
]
}

You must be logged in to vote

Replies: 3 comments 1 reply

Comment options

Yes, I encountered this issue as well. When the serializer gathers constraints from the model, it doesn’t account for the fact that a constraint might include a custom error message. Additionally, theUniqueTogetherValidator is created with a default message.https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L1595-L1621

You must be logged in to vote
0 replies
Comment options

Hi! I face to the same issue.

You must be logged in to vote
0 replies
Comment options

guys, any news? short workarounds?

You must be logged in to vote
1 reply
@s-aleshin
Comment options

I created a custom validator by subclassingUniqueTogetherValidator and overriding its__call__ method. This allows me to catch the default error and raise my ownValidationError with a custom message and error code.

classCustomUniqueTogetherValidator(UniqueTogetherValidator):def__call__(self,attrs,serializer):self.enforce_required_fields(attrs,serializer)try:super().__call__(attrs,serializer)exceptserializers.ValidationErrorasexc:            [msg]=exc.detailraiseserializers.ValidationError(str(msg),code="custom_unique_constraint"            )fromexcclassMySerializer(serializers.ModelSerializer):classMeta:model=MyModelfields="__all__"validators= [CustomUniqueTogetherValidator(queryset=MyModel.objects.filter(...).all(),fields=["field1","field2"],message="My custom message."            ),        ]

⚠️ When you override the validators attribute in your serializer’s Meta, it replaces all automatically generated validators based on model constraints (https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L1561-L1563). DRF will no longer auto-generate them — so you must explicitly define any additional validators you need (e.g., for other UniqueConstraints or CheckConstraints).

If an issue is opened based on this discussion, I’d be happy to submit a PR with a fix.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
General
Labels
None yet
4 participants
@AGM-90@s-aleshin@igdimer@soldatov-ss
Converted from issue

This discussion was converted from issue #9350 on March 28, 2024 10:16.


[8]ページ先頭

©2009-2025 Movatter.jp