Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add message_key to UniqueConstraintValidator for Structured Error Handling #9651

Closed

Conversation

m16bappi
Copy link

Problem:

The UniqueTogetherValidator previously raised validation errors as plain messages. This caused issues when dealing with non_related_fields, leading to inconsistencies in error structures. As a result:

  • Errors were difficult to associate with specific fields in frontend applications.
  • Validation messages were not properly structured, making it challenging to integrate with form-handling logic.
  • When non_related_fields were involved, the error response did not clearly indicate the affected field.

Solution:

  • Introduced a message_key parameter to the UniqueTogetherValidator.
  • If provided, the validation error will be returned as a dictionary with message_key as the key.
  • If message_key is not provided, the error will default to {non_related_field: "The fields race_name, position must make a unique set."} for clarity.

Example

Before (Without message_key)

class ErrorMessageKeySerializer(serializers.ModelSerializer):
    class Meta:
        model = UniquenessTogetherModel
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=UniquenessTogetherModel.objects.all(),
                fields=['race_name', 'position']
            )
        ]

Response:

{
  "non_related_field": ["The fields race_name, position must make a unique set."]
}

After (With message_key="name")

class ErrorMessageKeySerializer(serializers.ModelSerializer):
    class Meta:
        model = UniquenessTogetherModel
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=UniquenessTogetherModel.objects.all(),
                fields=['race_name', 'position'],
                message_key='name'
            )
        ]

Response:

{
  "name": ["The fields race_name, position must make a unique set."]
}

@m16bappi m16bappi closed this Feb 13, 2025
@m16bappi m16bappi deleted the feature/fix-search-in-browserable-api branch February 13, 2025 18:49
@m16bappi m16bappi restored the feature/fix-search-in-browserable-api branch February 13, 2025 18:49
@m16bappi m16bappi deleted the feature/fix-search-in-browserable-api branch February 13, 2025 18:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant