Search code examples
odooopenerp-7odoo-8openerp-8

What is the correct format to use Unique in _sql_constraints in OpenERP?


I have tried unique in sql_constaints in OpenERP(Odoo) using two different methods using flower brackets {} or square brackets []. Both works fine. Which one is correct?

_sql_constraints = {
    ('email_uniq', 'unique(email)', ' Please enter Unique Email id.')
    }

(or)

_sql_constraints = [
    ('email_uniq', 'unique(email)', ' Please enter Unique Email id.')
    ]

P.S: But if I want to use more than a constraint it accepting only square brackets [] like this example.

_sql_constraints = [
    ('email_uniq', 'unique(email)', ' Please enter Unique Email id.'),
    ('contact_uniq', 'unique(contact)', ' Please enter Unique Mobile no.')
    ]

What is the reason behind it?


Solution

  • The correct one is square brackets syntax.

    1. you can grep on _sql_constraints and see it is what is always used,

    2. in the ORM code in openerp/models.py we can see that the default value is an empty list:

        _sql_constraints = []
        #...
            cls._local_sql_constraints = cls.__dict__.get('_sql_constraints', [])
    
    1. in Odoo 8.0 documentation it is said:

    list of (name, sql_definition, message) triples defining SQL constraints to execute when generating the backing table.

    In python2 you can get a list with the syntax [].

    The syntax {} either creates:

    • a dictionary if it is empty {} or if there is keys values like this: {'keyA': 'valueA', 'keyB': 'valueB'},
    • as of python 2.7 a set if instantiated like this: {'value1', 'valueB', 42}