在 OpenERP 中使用 Unique in _sql_constraints 的正确格式是什么?

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

我在 OpenERP(Odoo) 的 sql_constaints 中尝试过 unique,使用两种不同的方法使用花括号 {} 或方括号 []。 两者都很好。 哪一个是正确的?

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

(或)

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

P.S:但是如果我想使用多个约束,它只接受方括号 [] 就像这个例子。

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

背后的原因是什么?

正确的是方括号语法。

  1. 你可以在 _sql_constraints 上 grep 看看它是一直使用的,

  2. openerp/models.py中的ORM代码中我们可以看到默认值为空列表:

    _sql_constraints = []
    #...
        cls._local_sql_constraints = cls.__dict__.get('_sql_constraints', [])
  1. Odoo 8.0 documentation中说:

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

在 python2 中,您可以使用语法 [].

获得 list

语法 {} 创建:

  • a dictionary 如果它是空的 {} 或者如果有这样的键值:{'keyA': 'valueA', 'keyB': 'valueB'},
  • as of python 2.7 a set 如果像这样实例化:{'value1', 'valueB', 42}

在 odoo 中,sql 约束的语法是 (name, sql_definition, message) 的列表。例如

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

你可以在元组列表中给出一个以上的 sql 约束。

当您定义没有键和值的字典时 python 将其视为集合。并且 set 可以是可迭代的。