Search code examples
pythonodooodoo-12

Filter employees by project in odoo 12


I'm customizing the Odoo project module, in the module, we have Projects that have tasks assigned to employees, I need to have a dropdown of employees based on the project selection, but because there isn't a direct relation I have to search all the tasks related to the project and then search for the employees.

this is my model so far:

class myModel(models.TransientModel):
    _name = "mymodule.mymodel"

    project_id = fields.Many2one('project.project', string="Project")
    task_id = fields.Many2one('project.task', string="Task", domain="[('project_id', '=', project_id)]")
    employee_id = fields.Many2one('hr.employee', string="Assign To")

    @api.onchange('project_id')
    def _projecy_onchange(self):
        if not self.project_id.id:
            return {'domain': {'employee_id': []}}
        
        tasks = self.env['project.task'].search([('project_id','=',self.project_id.id)])
                
        user_ids = []
        for t in tasks:
            if t.user_id:
              user_ids.append(t.user_id.id)
        
       
        if len(user_ids)>0:
            employees = self.env['hr.employee'].search(['user_id','in', user_ids])
            return {'domain': {'employee_id': employees}}
        else:
            return {'domain': {'employee_id': []}}

I'm having an issue when I want to search the employees:

employees = self.env['hr.employee'].search(['user_id','in', user_ids])

I get the following error:

elif token[1] == 'in' and not token[2]: IndexError: tuple index out of range

when I print user_ids is a basic list with the ids something like [9] (single element, cloud me more obviously)

I understand search can work as employees = self.env['hr.employee'].search(['user_id','in', [9])

any guidance will be appreciated


Solution

  • You have got the wrong syntax of odoo's search method do it like this,

    employees = self.env['hr.employee'].search([('user_id','in', user_ids)])
    

    Missing part from your syntax: round braces around your domain.