提问者:小点点

双字段的odoo添加验证


我有这个odo py

class CrmProject(models.Model):
_name='crm.project'
customer_id = fields.Many2one('res.partner','Customer')
project_product_id = fields.Many2one('crm.project.product','Project Product')

当customer_id和project_product_id与crm.project数据库中的值相同时,如何验证和显示警告?因此,必须首先检查数据库,然后显示警告,如果它与customer_idANDproject_product_id输入中的值相同。
例如:

Database table crm.project
customer_id = 1
project_product_id = 2

仅当输入:

customer_id = 1
project_product_id = 2

除此之外,不会创建任何警告

我已尝试过此操作,但未创建任何警告(更新25-04-2021)

@api.model
def create(self,vals):
    vals['name'] = self.env['ir.sequence'].next_by_code('crm.project')
    res = super(CrmProject,self).create(vals)
    # Add code here
    #res= super(CrmProject,self).create(vals)
    customer_id = vals.get('crm.project.customer_id')
    project_product_id = vals.get('crm.project.project_product_id')
    get_customer_id = self.env['crm.project'].search([('customer_id','=',customer_id)])
    get_project_product_id = self.env['crm.project'].search([('project_product_id','=',project_product_id)])
    if get_customer_id and get_project_product_id:
        raise UserError(_('The project has already been set before'))
    else:
        return res

任何帮助都将不胜感激


共1个答案

匿名用户

可以通过以下方式在数据库中创建约束:

create unique index name_your_constraint
on crm_project (customer_id, project_product_id);