Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CheckConstraint With IntegrityError

I have a constraint that I'd like to add in my Django Model. I thought the CheckConstraint method would help to catch the error when the input does not meet the constraint. However, when I saved the model with an invalid input, e.g. percentage = 101, an error page was shown with IntegrityError. Does anyone here know how to properly use this method to validate the input?

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=Q(percentage__gte=1)
                & Q(percentage__lte=100),
                name="Please enter a valid percentage",
            )
        ]

Solution: I ended up using this to solve my problem

    def clean_fields(self, exclude=None):
        super().clean_fields(exclude=exclude)
        if self.percentage and (
            self.percentage < 0 or self.percentage > 100
        ):
like image 219
SweetPotato Avatar asked Jul 11 '26 09:07

SweetPotato


1 Answers

The constraints are (only) enforced at the database side, and thus result in IntegrityErrors when the given condition is not met.

In order to raise the correct validation error, you add validators to the model fields, for example:

from django.core import validators

class MyModel(models.Model):
    percentage = models.IntegerField(validators=[
        validators.MinValueValidator(1),
        validators.MaxValueValidator(100)
    )]

    # …
like image 60
Willem Van Onsem Avatar answered Jul 13 '26 12:07

Willem Van Onsem