码迷,mamicode.com
首页 > 其他好文 > 详细

Odoo constraints 使用

时间:2017-12-14 13:32:07      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:res   装饰器   err   uniq   div   unique   方法   数据   包含   

在日常开发Odoo的过程中,我们不免要用到Constraints,中文就是约束。 
首先我们来介绍下Odoo里面的两种Constraints。

SQL Constraints:就是添加一个数据库的约束。 
_sql_constraints是odoo的属性,是一个元祖的列表,每个元祖是一个数据库约束。元祖的第一个元素是约束名字,第二个元素是约束规则(postgresql约束规则),第三个参数是如果违反约束弹出来的警告信息。

 _sql_constraints = [
        (name_description_check,
         CHECK(name != description),
         "The title of the course should not be the description"),

        (name_unique,
         UNIQUE(name),
         "The course title must be unique"),
    ]

 

注意在使用SQL Constraints,需要确保当前数据库里面没有违反该约束的数据,如果有违反约束的数据在更新模块的时候系统日志里面会有警告信息,大家要注意这个。

Constraints:

@api.constrains(instructor_id, attendee_ids)
    def _check_instructor_not_in_attendees(self):
        for r in self:
            if r.instructor_id and r.instructor_id in r.attendee_ids:
                raise exceptions.ValidationError("A session‘s instructor can‘t be an attendee")

 

odoo的Constraints,是通过装饰器@api.constrains(字段),每次记录修改的时候,如果包含了装饰器定义的字段就会触发下面的方法,所以需要在方法里面判断是否违反约束,如果违反,则通过raise异常来弹出警告框并阻止记录保存。使用odoo Constraints的时候就算是系统内已经有违反约束的记录也可以对新记录生效。

Odoo constraints 使用

标签:res   装饰器   err   uniq   div   unique   方法   数据   包含   

原文地址:http://www.cnblogs.com/brucexl/p/8036915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!