odoo 通过数据库验证

问题描述

我想在字段 customer_id 和 project_product_id 一起插入并与数据库检查时进行验证,如果两者与数据库相同则显示错误

我的py代码就像

_name='crm.project'
customer_id = fields.Many2one('res.partner','Customer')
@api.multi 
@api.constrains('customer_id','project_product_id')
def _check_total_value(self):
    target_list = []
    get_customer_id = self.customer_id
    get_project_product_id = self.project_product_id
self.env.cr.execute('''
                            select * 
                            from crm_project 
                            where customer_id = %s 
                                AND project_product_id = %s
                                
    ''',(get_customer_id,get_project_product_id))
    for target in self.env.cr.dictfetchall():
        target_list.append(target)
    if target_list:
        raise Warning("data duplicate")  

解决方法

检查数据库,如果两者都与数据库相同则显示错误

那么您的数据库中显然需要一个 UNIQUE constraint

不要在你的 python 代码中检查这些东西 - 当你在客户端应用程序中检查数据有效性而不是在数据库上时,有很多情况可能会出错等级。 More info

这就是make a database-level unique constraint in Odoo

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...