Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

544
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

over 4 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__'
    
over 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!