What is the main difference between clean and full_clean function in Django model ?
The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.
save() calls the clean. This way the integrity is enforced both from forms and from other calling code, the command line, and tests. Without this, there is (AFAICT) no way to write a test that ensures that a model has a FK relation to a specifically chosen (not default) other model.
to_python() method of the models. Field subclass (obviously for that to work you must write custom fields). Possible use cases: when it is absolutely neccessary to ensure, that an empty string doesn't get written into the database (blank=False keyword argument doesn't work here, it is for form validation only)
Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.
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.
they are not against each other usually you call Model.full_clean() to be able to trigger Model.clean() for costume 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With