OpenERP Unique约束

2024-10-04 05:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

它工作正常,但区分大小写。目前,它接受“米奇”、“米奇”和“米奇”等价值观:

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     |
--------------------------------

Tags: name名称sqlispostgresqlnotdescriptionopenerp
3条回答

以更简单的方式在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")

对于case insensitive constraints签出HERE 否则,您可以始终使用Openerp Constraints而不是SQL。

对于openerp约束

看看这个例子

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'])]

这样就不会从数据库中读取所有数据:

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'])]

相关问题 更多 >