March 2018
Beginner to intermediate
336 pages
8h 22m
English
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 ...
Read now
Unlock full access