Home > database >  Django-Rest-Framework can't override serializer unique error_messages
Django-Rest-Framework can't override serializer unique error_messages

Time:11-24

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

CodePudding user response:

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__'
    
  • Related