在插入数据 odoo 9 之前检查计数

Check count before insert data odoo 9

在自定义模块 odoo 9 中,如何在向数据库中插入新记录之前检查记录是否存在?

例如:

如果在 table project.task 中我们有名称 "PARIS" 和 date_deadline “2017-01-01” 在下面的代码中我需要在执行前发出警告...

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-02-02 和时间 = 1 的数据库中插入新记录后得到此消息:

重复键值违反唯一约束"test_module_time_uniq" 详细信息:密钥(时间)=(1)已经存在。

时间存在但日期不同!我需要 2 个值的约束!在数据库中,我只有一行,其中 date = 2017-01-01 和 time = 1

您可以按照这些思路使用:

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

如果你想防止重复记录使用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  

duplicate key value violates unique constraint "test_module_time_uniq" DETAIL: Key (time)=(1) already exists.

这个错误是由 postgres 抛出的,不是 odoo 你已经准备好对时间有一个独特的约束,只是你需要先放弃它

注意:谁添加了独特的约束,是您在测试代码时添加的还是其他人?通过评论回答^^

ALTER TABLE project_task DROP CONSTRAINT test_module_time_uniq;