1. _sql_constraints
_sql_constraints:是模型类的一个属性,意思是添加一个数据库的约束
- 值是一个列表套元组形式,每个元祖是一个数据库约束。
- 元祖的第一个元素是约束名字,
- 第二个元素是约束规则(postgresql约束规则),
- 第三个参数是如果违反约束弹出来的警告信息。
用法如下:
class HrpDepartmentModel(models.Model): _name = 'school.hr.department' _description = '部门信息表' _rec_name = 'dep_name' _sql_constraints = [ ('dep_code_unique', 'unique(dep_code)', '部门编号不能重复'), ('emp_number_check', 'check(emp_number > 0)', '部门员工数量不能为0') ] dep_code = fields.Char(string='部门编号', required=True) dep_name = fields.Char(string='部门名称', required=True) address = fields.Char(string='部门地址') telephone = fields.Char(string='部门电话') emp_number = fields.Integer(string='部门员工数量', default=10)
例如这个元组,就是一个约束
('dep_code_unique', 'unique(dep_code)', '部门编号不能重复')
- dep_code_unique是约束的名称,是元组中的第一个参数
'unique(dep_code)', 是约束的规则,可参考下方链接 https://www.imangodoc.com/45029.htmlhttps://www.imangodoc.com/45029.html 括号里面是模型类的字段名称- 元组中第三个是,提示的信息,效果如下图
其他的约束也是类似的
注意: 在加入约束的时候,最好你的数据库表的数据没有违反该约束的数据,如果有违反的,可以到后台控制台日志里面看到有提示。
odoo中的字段约束
最新推荐文章于 2024-05-07 16:34:00 发布