Model constraints
To enforce data integrity, models also support two types of constraints: SQL and Python.
SQL constraints are added to the database table definition and are enforced directly by PostgreSQL. They are defined using the _sql_constraints
class attribute. It is a list of tuples with the constraint identifier name, the SQL for the constraint, and the error message to use.
A common use case is to add unique constraints to models. Suppose we don't want to allow two active tasks with the same title, as follows:
# class TodoTask(models.Model): _sql_constraints = [ ('todo_task_name_uniq', # Constraint unique identifier 'UNIQUE (name, active)', # Constraint SQL syntax 'Task title must be unique!') # Validation message ]
Python constraints can use a piece of arbitrary code to check the conditions. The checking function should be decorated with @api.constrains
and the indication of the list of fields involved in the check. The validation is triggered...