We will edit the LibraryBook class in the models/library_book.py Python file:
- To create the database constraint, add a model attribute:
class LibraryBook(models.Model): # ... _sql_constraints = [ ('name_uniq', 'UNIQUE (name)', 'Book title must be unique.') ]
- To create the Python code constraint, add a model method:
from odoo import api, models
from odoo.exceptions import ValidationError
class LibraryBook(models.Model): # ... @api.constrains('date_release') def _check_release_date(self):
for record in self:
if record.date_release and
record.date_release > fields.Date.today():
raise models.ValidationError(
'Release date must be in the past')
After these changes are made to the code file, an add-on module upgrade and a server restart are needed.