【问题标题】:Check count before insert data odoo 9在插入数据odoo 9之前检查计数
【发布时间】:2017-04-05 21:14:32
【问题描述】:

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

例如:

如果在表 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)

或者在点击按钮保存之前尝试从 name='PARIS' 和 date_deadline='2017-01-01' 的 project.task 获取计数!

任何简单的解决方案?

@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” DETAIL:键(时间)=(1)已经存在。

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

【问题讨论】:

  • 您在时间字段上定义了一个 sql 唯一约束 (test_module_time_uniq)。你只需要删除它,它应该可以工作。

标签: openerp odoo-9


【解决方案1】:

如果你想防止重复记录使用 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” DETAIL:键(时间)=(1)已经存在。

这个错误是由 postgres 而不是 odoo 引发的,你已经准备好对时间有一个独特的限制,只是你需要先删除它

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

ALTER TABLE project_task DROP CONSTRAINT test_module_time_uniq;

【讨论】:

  • 卸载后重新安装模块一切正常!
  • 是的,因为您在 odoo 中添加了约束,然后您删除了代码,但 odoo 在创建它后不会删除约束,这就是为什么。请记住,您在 odoo 中定义了一些想法,不要删除代码,而是取消设置,例如,如果您这样做 [something],请不要删除它但取消设置值 [] 否则域会在那里窃取,但你不会按照你想要的结果...
【解决方案2】:

你可以按照这些思路使用一些东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多