在自定义模块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)或者,在点击“保存”按钮之前,可以尝试从project.task获得名称=‘PARIS’和日期_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“细节: key (time)=(1)已经存在。
时间是存在的,但日期是不同的!我需要2值的约束!在数据库中,我只有一行,日期= 2017-01-01,时间=1。
发布于 2017-04-04 15:16:09
如果要防止重复记录,请使用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“细节: key (time)=(1)已经存在。
这个错误是由postgres抛出的,不是odoo,您已经准备好了,对时间有一个唯一的约束,只需要先删除它。
注:谁添加的约束唯一,是你在哪里测试你的代码,还是其他人?请用注释^^回答这个问题。
ALTER TABLE project_task DROP CONSTRAINT test_module_time_uniq;发布于 2017-04-04 13:29:02
您可以使用类似这样的东西:
@api.constrains('name', 'date_deadline')
def _check_existing(self):
# Search for entry with these params, and if found:
# raise ValidationError('Item already exists')https://stackoverflow.com/questions/43207985
复制相似问题