liveBook · Manning

Clean()

As explained in Django in Action

clean() is a Django model method that performs object-level validation and can raise a validation error for invalid field relationships.

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

How Django in Action covers it

How deep it goes
Explains overriding clean(), raising ValidationError, and the important limit that saves do not call it automatically.
Examples
Demonstrates conditional musician and band foreign-key requirements in the RiffMates SeekingAd model.
What it assumes
Assumes basic ORM field validation and introduces object-level checks for relationships among model fields.
What you can do after
Apply it by overriding a model’s clean() method to reject invalid combinations of field values.
How it connects
Connects model validation with field-level validation, ValidationError, Django Admin, and ModelForm processing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.