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