python / intermediate
Snippet
Enforcing Model Level Integrity Constraints with clean()
Overriding the model's `clean()` method allows validating relationship dependencies across multiple model fields before saving records.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
from django.db import modelsfrom django.core.exceptions import ValidationErrorclass Event(models.Model):start_date = models.DateField()end_date = models.DateField()def clean(self):if self.end_date < self.start_date:raise ValidationError("End date cannot precede start date.")
django
Breakdown
1
from django.db import models
Imports Django database model base classes and field definitions.
2
from django.core.exceptions import ValidationError
Imports ValidationError to signal model validation failures.
3
class Event(models.Model):
Defines a database model class representing an event.
4
start_date = models.DateField()
Defines a date field for the event start time.
5
end_date = models.DateField()
Defines a date field for the event end time.
6
def clean(self):
Overrides the model clean hook for cross-field validation logic.
7
if self.end_date < self.start_date:
Checks if the end date occurs chronologically before the start date.
8
raise ValidationError("End date cannot precede start date.")
Raises a ValidationError when date sequencing is illogical.