14

我在 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     |
--------------------------------
4

3 回答 3

16

要在此处case insensitive constraints查看 其他内容,您始终可以使用 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'])]
于 2012-11-07T05:25:51.777 回答
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'])]
于 2018-04-26T15:33:41.960 回答
-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")
于 2018-02-22T22:59:43.453 回答