约束可以有两种类型。
数据库约束
当您升级该模块时,数据库约束将在数据库级别添加验证。数据库约束是元组列表,其中元组包含三个参数。
_sql_constraints = [
('constrain name', 'unique(field1, field2)', 'error message which you want to raise on constrains violation'),
('constrain name', 'constrains defination', 'error message which you want to raise on constrains violation'),
]
- 约束名称
- 约束,如唯一,检查
可以将唯一约束应用于许多列。
- 错误信息
例子:
_sql_constraints = [
('uniq_vat', 'unique(vat)', 'It already exists another company with the same TIN!'),
]
多个数据库约束可以加在一起。
应用程序约束
应用程序约束用于在记录添加、更新和删除时触发自定义验证。简而言之,如果记录发生任何更改,您的自定义方法将被调用。
如何在代码中定义约束。
@api.constrains('field1','field2'....)
约束可以同时应用于多个字段,也可以单独定义。
@api.constrains('vat')
def check_vatnumber(self):
for record in self:
obj = self.search([('vat','=',record.vat),('id','!=',record.id)])
if obj:
raise Warning("Warning", "It already exists another company with the same TIN!")