SQL Constraints
_sql_constraints = [
('unique_name','unique_name(name)','名称必须唯一') ,
("qweb_required_key","CHECK (type!='qeb' OR key Is NOT NULL)","Invalid inheritance mode:if the mode is ''extension,this view must extend an other")
]
在odoo中通过模型属性 _sql_constraints 来实现给数据库添加一个数据库层面的约束条件。
格式: 约束名称 , 约束规则 , 警告信息
不再使用该约束时
//
_sql_constraints = [
('unique_name','unique_name(name)','名称必须唯一') # 原
('unique_name','Check(1=1)','名称必须唯一') # 改
]
Odoo @api .Constraints
@api.constrains('uom_id', 'uom_po_id')
def _check_uom(self):
if any(template.uom_id and template.uom_po_id and template.uom_id.category_id != template.uom_po_id.category_id for template in self):
raise ValidationError(_('The default Unit of Measure and the purchase Unit of Measure must be in the same category.'))
return True
Odoo的Constraints,通过装饰器@api.constraints(field_name)来定义,里面可以添加复杂的逻辑,每次修改时如果包含了装饰器定义的字段就会触发,通过 raise 阻止保存。
注:@api.constraints 系统内已有违反约束的记录也可以对新记录生效