首页 > 解决方案 > odoo validate by database

问题描述

I want to make validation when both field customer_id and project_product_id inserted together and checked with the database and show error if both are the same with the database

My py code is like

_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")  

标签: odooodoo-8odoo-10odoo-9

解决方案


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

那么您显然需要在数据库中使用UNIQUE 约束

不要在你的 python 代码中检查这些东西——当你在客户端应用程序中检查数据有效性时,有几十种情况可能会出错,但不是在数据库级别。更多信息

这就是如何在 Odoo 中创建数据库级唯一约束


推荐阅读