'Model.clean() vs Model.clean_fields()

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.



Solution 1:[1]

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 toe 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1