odoo 为双字段添加验证

问题描述

我有这个 odoo 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_id 和 project_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

任何帮助将不胜感激

解决方法

您可以使用以下命令在您的数据库中创建约束:

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

相关问答

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