Search code examples
python-3.xodoo-12

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


Solution

  • Please use the below code for checking

    @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)
    

    Please be informed that we cannot loop res in create that is not a right method and in your code you are checking the conditions after creating the record so always the search result will be true.