What is the difference between the Model.clean()
method and the Model.clean_fields()
method?. When should I use one or the other?.
According to the Model.clean_fields()
method documentation:
This method will validate all fields on your model. The optional exclude argument lets you provide a list of field names to exclude from validation. It will raise a ValidationError if any fields fail validation.
. . .
So the Model.clean_fields()
method is used to validate the fields of my model.
According to the Model.clean()
method documentation:
This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field
. . .
But, this method should be used to make other validations, but among those, you can perform validations to different fields. And in the Django examples of the Model.clean()
method, validations are made to fields:
class Article(models.Model):
...
def clean(self):
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
raise ValidationError(_('Draft entries may not have a publication date.'))
# Set the pub_date for published items if it hasn't been set already.
if self.status == 'published' and self.pub_date is None:
self.pub_date = datetime.date.today()
So for example, if I want to validate a field, in which of the two methods should I do it?
And for what exactly should the methods be used? since I don't understand very well why they should be used exactly. It would be very helpful to provide examples where you can see the difference between the methods, to know exactly what the methods should be used for.
clean_fields
will call the cleaning methods, and validators of the indidual fields, you normally do not overrideclean_fields
.