有没有办法检查 Many2one res.users 记录是否已经存在
Is there a way to check if Many2one res.users record exists already
I'm creating my own module to manage agents accounts in odoo. where i do need to verify if a res.user if already in agent, to avoid creating agent with the same res.user account
class Agent(models.Model):
_name = 'agent.a'
agent_id = fields.Many2one(
'res.users',
string='Agent',
default=lambda s: s.env.user)
agent_image = fields.Binary(string='Photo')
local_id = fields.One2many('local.n', 'Localisation_Af', string='Localisation')
@api.model
def create(self, vals):
res = super(Agent, self).create(vals)
modelObj = self.env['agent.a']
for record in res:
rec = modelObj.search([('agent_id', '=', record.agent_id.login)])
if rec:
raise ValidationError(('Already exists'))
else:
return res
But the result is always True
请使用以下代码进行检查
@api.model
def create(self, vals):
if vals.get('agent_id',False):
modelObj = self.env['agent.a']
rec = modelObj.search([('agent_id', '=', vals.get('agent_id',False))])
if rec:
raise ValidationError(('Already exists'))
return super(Agent, self).create(vals)
请注意,我们不能在 create 中循环 res,这不是正确的方法,并且在您的代码中,您在创建记录后检查条件,因此搜索结果始终为真。
I'm creating my own module to manage agents accounts in odoo. where i do need to verify if a res.user if already in agent, to avoid creating agent with the same res.user account
class Agent(models.Model):
_name = 'agent.a'
agent_id = fields.Many2one(
'res.users',
string='Agent',
default=lambda s: s.env.user)
agent_image = fields.Binary(string='Photo')
local_id = fields.One2many('local.n', 'Localisation_Af', string='Localisation')
@api.model
def create(self, vals):
res = super(Agent, self).create(vals)
modelObj = self.env['agent.a']
for record in res:
rec = modelObj.search([('agent_id', '=', record.agent_id.login)])
if rec:
raise ValidationError(('Already exists'))
else:
return res
But the result is always True
请使用以下代码进行检查
@api.model
def create(self, vals):
if vals.get('agent_id',False):
modelObj = self.env['agent.a']
rec = modelObj.search([('agent_id', '=', vals.get('agent_id',False))])
if rec:
raise ValidationError(('Already exists'))
return super(Agent, self).create(vals)
请注意,我们不能在 create 中循环 res,这不是正确的方法,并且在您的代码中,您在创建记录后检查条件,因此搜索结果始终为真。