2017-05-24 85 views
0

我想對字段(TIN)進行控制檢查,以便每次創建新客戶時,TIN都應該是唯一的。如果其他客戶擁有該TIN,則必須顯示錯誤消息。 我想這句法:如何對字段進行約束

_sql_constraints=[('uniq_vat', 'UNIQUE(self.env.vat)', 
'It already exists another company with the same TIN!')] 

我使用odoo 10

+0

,而不是簡單地self.env.vat要給外地的名字(你的情況TIN) –

回答

1
_sql_constraints = [('unique_tin_no', 'unique(field_name)', 'It already exists another company with the same TIN!')] 
+0

請儘量避免剛剛傾倒的代碼作爲一個答案,並試圖解釋它做什麼,以及爲什麼。對於那些沒有相關編碼經驗的人來說,你的代碼可能並不明顯。 – Frits

0

小的變化是在你行,你的約束正常工作

_sql_constraints=[('uniq_vat', 'unique(vat)', 'It already exists another company with the same TIN!')] 

你只需要將「vat」替換爲「self.env.vat」sql_constrains只需要將要應用於下面的數據庫表的字段名稱。

1

約束可以有兩種類型。

  • 應用約束
  • 數據庫約束

數據庫約束

數據庫的約束將在數據庫級別添加驗證,而你升級模塊。數據庫約束是元組列表,其中元組包含三個參數。

_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'), 
] 
  1. 約束命名
  2. 約束,喜歡獨特的,檢查 唯一約束可以應用到許多列。
  3. 錯誤消息

實施例:

_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!") 
+0

很好地解釋了答案 –