Odoo constraints 使用教程

在日常開發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的時候就算是系統內已經有違反約束的記錄也可以對新記錄生效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章