Reputation: 894
What is the main difference between clean and full_clean function in Django model ?
Upvotes: 20
Views: 13293
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
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
Reputation: 7238
From the documentation:
Model.full_clean(exclude=None, validate_unique=True):
This method calls
Model.clean_fields()
,Model.clean()
, andModel.validate_unique()
(ifvalidate_unique
isTrue
), in that order and raises aValidationError
that has amessage_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