O'Reilly logo

Odoo Development Essentials by Daniel Reis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Model constraints

To enforce data integrity, models also support two types of constraints: SQL and Python.

SQL constraints are added to the table definition in the database and implemented by PostgreSQL. They are defined using the class attribute _sql_constraints. 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 didn't want to allow the same user to have two active tasks with the same title:

# class TodoTask(models.Model):
    _sql_constraints = [
        ('todo_task_name_uniq',
         'UNIQUE (name, user_id, active)',
         'Task title must be unique!')]

Since we are using the user_id field added by the todo_user module, this dependency ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required