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 ...

Get Odoo 11 Development Essentials - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.