How to add Check Constraints for Django Model fields?
check-constraints, django, django-forms, django-models
Solution
I would not put constraints like these in the save method, it's too late. Raising an exception there, doesn't help the user who entered the data in the wrong way, because it will end up as a 500 and the user won't get the form with errors back etc.
You should really check for this in the Forms/ModelForms clean method and raise a ValidationError, so `form.is_valid()` returns false and you can send the errors in the form back to the user for correction.
Also note that since version 1.2, Django has had Model Validation.
It would look something like this:
class Foo(models.Model):
# ... model stuff...
def clean(self):
if self.start_date > self.end_date:
raise ValidationError('Start date is after end date')
Problem
While subclassing `db.models.Model`, sometimes it's essential to add extra checks/constraints. For example, I have an `Event` model with `start_date` and `end_date`: I want to add validation into the fields or the model so that `end_date > start_date`. At least I know this can be done outside the `models.Model` inside the `ModelForm` validation. But how to attach to the fields and the `models.Model`?