5.14. Models Method Clean
Model.clean_fields()- Validate the model fieldsModel.clean()- Validate the model as a wholeModel.validate_unique()- Validate the field uniquenessModel.validate_constraints()- Validate the constraintshttps://docs.djangoproject.com/en/stable/ref/models/instances/#validating-objects
Model.full_clean(), and ``Model.clean()methods are not invoked when you call your model'ssave()method, you need to call it manually before saving the model instance.
There are four 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()Validate the constraints -
Model.validate_constraints()
All four steps are performed when you call a model's full_clean() method.
5.14.1. Clean
This method should be used to provide custom model validation, and to modify attributes on your model if desired.
Model's
.clean()method is not invoked when you call your model's.save()method.
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:
>>> #
... from django.db import models
... from django.utils.translation import gettext_lazy as _
...
...
... class Customer(models.Model):
... firstname = models.CharField(verbose_name=_('First Name'), max_length=50)
... lastname = models.CharField(verbose_name=_('Last Name'), max_length=50, db_index=True)
...
... def clean(self):
... # to run this method, you need to call .full_clean() on the object before saving
... if '@' in self.firstname:
... raise ValidationError('Firstname contains invalid character')
... if '@' in self.lastname:
... raise ValidationError('Lastname contains invalid character')
...
... def __str__(self):
... return f'{self.firstname} {self.lastname}'
...
... class Meta:
... verbose_name = _('Customer')
... verbose_name_plural = _('Customers')
5.14.2. Use Case - 1
>>> #
... import string
... from datetime import date
... from django.core.exceptions import ValidationError
... from django.db import models
... from django.utils.translation import gettext_lazy as _
...
...
... class Department(models.Model):
... name = models.CharField(verbose_name=_('Name'), max_length=15, db_index=True, unique=True, null=False, blank=False)
... employees = models.ManyToManyField(verbose_name=_('Employees'), to='company.Employee', related_name='departments', blank=True, default=None)
...
... def clean(self):
... # to run this method, you need to call .full_clean() on the object before saving
... lowercase = tuple(string.ascii_lowercase)
... if self.name.startswith(lowercase):
... raise ValidationError('Department name cannot start with lowercase letter')
...
... def __str__(self):
... return self.name
...
... class Meta:
... verbose_name = _('Department')
... verbose_name_plural = _('Departments')
...