5

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?

ea-
  • 356
  • 2
  • 8
Tintumon M
  • 1,156
  • 2
  • 14
  • 36

2 Answers2

7

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}
ea-
  • 356
  • 2
  • 8
  • 1
    But it creates _sql_constraints when I use {} . Even for multiple constraints. – Tintumon M Jul 21 '15 at 09:39
  • 1
    @ea- +1 for Nice explanation! – Atul Arvind Jul 21 '15 at 12:07
  • 1
    @TintuMon it may work by luck currently in core odoo. A list and a set can often be used interchangeably in python. Using a set you would gain no advantage, and you could get an error with a futur change in Odoo or with an external module which may expect the sql constraint list to be be a _list_. – ea- Jul 21 '15 at 15:37
  • 1
    Thank you @AtulArvind I"ll follow this in future to avoid error. – Tintumon M Jul 22 '15 at 05:21
5

In odoo the syntax for sql constraint is list of (name, sql_definition, message). for example

_sql_constraints = [
    ('name_uniq', 'unique(name)', 'Custom Warning Message'),
    ('contact_uniq', 'unique(contact)', 'Custom Warning Message')
]

you can give more then one sql constraint in list of tuples.

when you define a dictionary with out key & value python treat it as set. and set can be itrable.

Atul Arvind
  • 16,054
  • 6
  • 50
  • 58