• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

479
Views
Django-Rest-Framework can't override serializer unique error_messages

I have the following model:

class PersonDiscount(models.Model):
    user = models.OneToOneField('backend.Customer', related_name='discount', on_delete=models.CASCADE, error_messages={
        'unique': _('A discount setting is already set up for this customer.')})
    discount = models.IntegerField(default=0)
    discount_auto = models.IntegerField(default=0)
    auto = models.BooleanField(default=True)

    class Meta:
        ordering = ['-id']

And a following serializer for the model:

class PersonDiscountPostSerializer(serializers.ModelSerializer):
    class Meta:
        model = PersonDiscount
        fields = '__all__'
        extra_kwargs = {
            'user': {
                'error_messages': {
                    'unique': _('A discount setting is already set up for this customer.')
                }
            }
        }

When i tried to create a PersonDiscount instance with existed user from the api i'm not getting the custom error message which i set in both model and serializer.

{
  "user": [
    "This field must be unique."
  ]
}

I had already looked up in the docs and can't find any other way to understand why the override error_messages not getting applied. I also restarted the django runserver several times already

Hope someone can help me with this problem

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

You can validate uniqueness manually as below:

class PersonDiscountPostSerializer(serializers.ModelSerializer):

    user = serializers.PrimaryKeyRelatedField(
        required=True, 
        queryset=Customer.objects.all(),
    )

    def validate_user(self, value):
        exists = PersonDiscount.objects.filter(user=value).exists()
        if exists:
            raise serializers.ValidationError("err msg")
        return value

    class Meta:
        model = PersonDiscount
        fields = '__all__'
    
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error