SweetPotato
SweetPotato

Reputation: 61

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
        ):

Upvotes: 3

Views: 1141

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477264

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)
    )]

    # …

Upvotes: 1

Related Questions