clean() is a Django model method for validating relationships between fields. Field rules can reject empty or malformed values, but they cannot normally express dependencies such as “when seeking a musician, a band must be selected.” Override clean() to inspect the whole object and raise ValidationError when its combination of values is invalid. section 7.2.1
Validating a RiffMates classified ad
A SeekingAd records whether someone is seeking a musician or a band. Its seeking field determines which foreign key must be populated: musician when seeking a band, or band when seeking a musician. The model’s clean() method checks that relationship and raises a ValidationError with a useful message when the required field is missing. section 7.2.1
def clean(self):
if self.seeking == MusicianBandChoice.MUSICIAN:
if self.band is None:
raise ValidationError(
"Band field required when seeking a musician")
...
Use the compact validation pattern as a template: compare the choice field, check the related field, and raise ValidationError when the combination is not allowed. section 7.2.1
Keep these practical cautions in mind:
- clean() is not called automatically when an ORM object is saved, so programmatically created objects can bypass this validation. section 7.2.1
- Django Admin calls the validation methods, making the rule effective during normal admin form processing. section 7.2.1
- Use clean() for object-level rules; keep independent requirements and simple constraints at the field level. section 7.2.1
