我已经为此苦苦挣扎了一段时间。这两个选项都不起作用,也没有给出错误。我把pythonic constrain方法注释掉给你看。
代码片段:
class house_development(models.Model):
_name = 'house.development'
_description = 'Development'
_inherit = ["mail.thread"]
name = fields.Char(string="Name", required=True, track_visibility='onchange')
description = fields.Text(string="Description", track_visibility='onchange')
# @api.one
# @api.constrains('name')
# def _identify_same_name(self):
# for record in self:
# if record.name in self:
# raise exceptions.ValidationError("There is another development/project with the same name: %s" % record.name)
_sql_constraints = [
('name_unique',
'UNIQUE(name)',
"There is another development/project with the same name"),
]
最佳答案
应该是这样的
@api.multi
@api.constrains('name')
def _identify_same_name(self):
for record in self:
obj = self.search([('name','=ilike',record.name),('id','!=',record.id)])
if obj:
raise exceptions.ValidationError("There is another development/project with the same name: %s" % record.name)
您需要搜索相同的名称但不是相同的 id。
对于数据库唯一约束,您可以这样添加。
_sql_constraints = [
('name_unique', 'unique(name)', 'There is another development/project with the same name!!!'),
]
Database constrains will not be added if there are duplicate name in table. Sql constrains will apply only if the rule is not violated by the existing data. I think in your case that's the point with Sql constrains. And make sure for that you need to upgrade module. first check duplicate records in database by firing that query.
Select name, count(*) from table_name
group by name
having count(*) > 1;
odoo 域中的可用运算符 Click to see more .
关于methods - sql 和 python 约束在 odoo 9 中都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45235527/