4.14. Models Method Clean
>>>
... 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')
4.14.1. 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')
...