OpenERP唯一约束

时间:2012-11-07 05:18:59

标签: python openerp

我在OpenERP / PostgreSQL中有一个表,其中包含以下列:namedescription

我为唯一名称添加了以下验证:

_sql_constraints = [('unique_name', 'unique(name)', 'A record with the same name already exists.')]

它工作正常,但它区分大小写。目前,它接受诸如“Mickey”,“MICKEY”和“mickey”之类的值:

Wrong Way:
--------------------------
| name   | description   |
--------------------------
| mickey | not a mouse   |
--------------------------
| MICKEY | not a mouse   |
--------------------------
| Mickey | not a mouse   |
--------------------------

有没有办法修改验证码,以便它不允许用户添加多个值,如“Mickey”,“MICKEY”和“mickey”?如何使唯一密钥验证不敏感?

Right Way:
--------------------------------
| name         | description   |
--------------------------------
| mickey       | not a mouse   |
--------------------------------
| mickey mouse | is a mouse    |
--------------------------------
| donald       | is a duck     |
--------------------------------

3 个答案:

答案 0 :(得分:15)

case insensitive constraints结帐HERE 否则你总是可以使用Openerp Constraints而不是SQL。

for openerp Constraints

检查示例

def _check_unique_insesitive(self, cr, uid, ids, context=None):
    sr_ids = self.search(cr, 1 ,[], context=context)
    lst = [
            x.FIELD.lower() for x in self.browse(cr, uid, sr_ids, context=context)
            if x.FIELD and x.id not in ids
          ]
    for self_obj in self.browse(cr, uid, ids, context=context):
        if self_obj.FILD and self_obj.FILD.lower() in  lst:
            return False
    return True

_constraints = [(_check_unique_insesitive, 'Error: UNIQUE MSG', ['FIELD'])]

答案 1 :(得分:1)

这种方式无需读取数据库中的所有数据:

def _check_unique_insesitive(self, cr, uid, ids, context=None):

    for self_obj in self.browse(cr, uid, ids, context=context):
        if self_obj.name and self.search_count(cr, uid, [('name', '=ilike', self_obj.name), ('id', '!=', self_obj.id)], context=context) != 0:
            return False

    return True

_constraints = [(_check_unique_insesitive, _('The name must be unique!'), ['name'])]

答案 2 :(得分:-1)

以更简单的方式在Odoo 8.0或更高版本中使用约束。 获取模型的所有记录,并使用lower()检查所需的字段值,并排除自记录。

@api.constrains('code')
def _check_duplicate_code(self):
    codes = self.search([])
        for c in codes:
            if self.code.lower() == c.code.lower() and self.id != c.id:
                raise exceptions.ValidationError("Error: code must be unique")