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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM