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
):
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)
)]
# …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With