2017-04-04 28 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') 
相关问题