2017-04-04 29 views
0

如何在自定義模塊odoo 9之前在數據庫中插入新記錄,檢查記錄是否存在?插入數據之前檢查計數odoo 9

例如:

如果表project.task我們的名字 「PARIS」 和date_deadline 「2017年1月1日」,在下面的代碼我需要警告之前執行...

vals = {'name': 'PARIS','date_deadline': '2017-01-01']} 
create_new_task = http.request.env['project.task'].create(vals) 

或者,也許嘗試從project.task獲得計數,其中name ='PARIS'和date_deadline ='2017-01-01',然後單擊按鈕保存!

任何簡單的解決方案?

@api.one 
@api.constrains('date','time') #Time is Many2one 
    def _check_existing(self): 
     count = self.env['test.module'].search_count([('date','=',self.date),('time','=',self.time.id)]) 
     print(self.date) #2017-01-01 
     print(self.time.id) #1 
     if(count >= 1): 
      raise ValidationError(_('DUPLICATE!')) 

嘗試在數據庫,在那裏是日期= 2017年2月2日和時間插入新記錄= 1後,得到這個消息:

重複鍵值違反唯一約束「test_module_time_uniq」 詳細信息:按鍵(時間)=(1)已經存在。

時間存在但日期不同!我需要約束2值!在DATABSE我只有一個列在哪裏日期= 2017年1月1日和時間= 1

+0

你對時間字段('test_module_time_uniq')定義的SQL唯一約束。你只需要刪除它,它應該工作。 – dgeorgiev

回答

2
如果要防止重複記錄使用sql_constrains

class ModelClass(models.Model): 
    _name = 'model.name' 
    # your fields ... 

    # add unique constraints 
    sql_constraints = [ 
      ('name_task_uniq', 'UNIQUE (name,date_deadline)', 'all ready got a task with this name and this date') 
     ] 

    # or use api.constrains if you constrains cannot be don in postgreSQL 
    @api.constrains('name', 'date_deadline') 
    def _check_existing(self): 
     # add you logic to check you constrain 

重複鍵值違反唯一約束 「test_module_time_uniq」 詳細信息:按鍵(時間)=(1)已經存在。

此錯誤是由Postgres的拋出不odoo你們都準備好了嗎有時間的唯一約束只需要刪除它首先

NB:誰添加的約束獨特之處是它時,你在那裏測試你代碼還是別人?通過評論回答這個^^

ALTER TABLE project_task DROP CONSTRAINT test_module_time_uniq; 
+0

卸載後,再次安裝模塊一切正常! –

+0

是的,因爲你在odoo中添加了約束,那麼你刪除了代碼,但odoo在創建它之後不會刪除約束。請記住,你可以在odoo中定義一些想法,不要刪除代碼,但如果例如在動作中取消設置,如果你做了 [某事]不刪除它,但取消設置值 []否則該域名將在那裏竊取,但你不會得到它不是你想要的結果... – Cherif

2

您可以使用類似的規定:

@api.constrains('name', 'date_deadline') 
def _check_existing(self): 
    # Search for entry with these params, and if found: 
     # raise ValidationError('Item already exists') 
相關問題