kamyarmg
kamyarmg

Reputation: 894

What is the main difference between clean and full_clean function in Django?

What is the main difference between clean and full_clean function in Django model ?

Upvotes: 20

Views: 13293

Answers (3)

amirbahador
amirbahador

Reputation: 121

They are not against each other. Usually you call Model.full_clean(), which calls Model.clean() for custom validation. For example:

from django.core.exceptions import ValidationError
from django.db import models


class Brand(models.Model):
    title = models.CharField(max_length=512)

    def clean(self):
        if self.title.isdigit():
            raise ValidationError("title must be meaningful not only digits")

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)

Upvotes: 4

kamyarmg
kamyarmg

Reputation: 894

here are three steps involved in validating a model:

Validate the model fields - Model.clean_fields()

Validate the model as a whole - Model.clean()

Validate the field uniqueness - Model.validate_unique()

All three steps are performed when you call a model’s full_clean() method. for more information click here

Upvotes: 2

Keyur Potdar
Keyur Potdar

Reputation: 7238

From the documentation:

Model.full_clean(exclude=None, validate_unique=True):

This method calls Model.clean_fields(), Model.clean(), and Model.validate_unique() (if validate_unique is True), in that order and raises a ValidationError that has a message_dict attribute containing errors from all three stages.

Model.clean():

This method should be used to provide custom model validation, and to modify attributes on your model if desired.

For more detailed explanation, have a look at the Validating objects section of the documentation.

Upvotes: 16

Related Questions