7

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.

1
  • clean_fields will call the cleaning methods, and validators of the indidual fields, you normally do not override clean_fields. Apr 29, 2020 at 17:29

1 Answer 1

8

if I want to validate a field, in which of the two methods should I do it?

Then you add that normally as validator [Django-doc]:

from django.core.exceptions import ValidationError

def even_validator(value):
    if value % 2:
        ValidationError('The value should be even')

class MyModel(models.Model):
    my_fields = models.IntegerField(validators=[even_validator])

The .clean_fields() method [Django-doc] will then call the cleaning methods and validation methods of the individual fields, and you can pass parameters to specify if you want to exclude validating a certain field. But normally you do not override .clean_fields() itself.

The .clean() method [Django-doc] on the other hand is a validation method that is used if multiple fields are involved. You can override this, although in that case you normally also call the super().clean() method to do validations defined at the base class.

4
  • the clean() method in the Model base class is empty. So I don't think a call to 'super' is necessary.
    – aaronn
    May 4, 2022 at 9:38
  • 1
    @aaronn: if you have multiple parent classes (for example when using mixins, abstract models, etc.), it walks up the MRO, therefore it is always better to call the super method. May 4, 2022 at 9:42
  • 1
    Oh, you are right. But in case that the ValidationError in clean() is raised, the call to super will not be reached and possible errors in there will be ignored. (assuming super().clean() is at the bottom of the clean method; otherwise, the problem still exists but it's the other way around)
    – aaronn
    May 4, 2022 at 10:07
  • @aaronn: normally this is why one calls full_clean(), this will call clean_fields(), clean() and validate_unique(). May 4, 2022 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.