Search code examples
pythonodooodoo-15

search method optimization for searching field area in odoo15


I have a function

    def test(self):
        tech_line = self.env['tech_line']
        allocated_technician = self.env['allocated_technician']
        users = self.env['res.users']
        tech_line = tech_line.search(
            [('service_type_id', '=', self.service_type_id.id)])
        al_a6 = self.env['tech_line'].filtered(lambda rec: rec.service_type_id.id == self.service_type_id.id)

        area = []
        area_new = []
        for tec in tech_line:
            territory = self.env['territory']
            territories = territory.search(
                [('technicians', 'in', tec.technician_allociated_id.user_id.id)])

            territories_lam = self.env['territory'].filtered(
                lambda t_lam: t_lam.technicians.id in tec.technician_allociated_id.user_id.id)

            for territory in territories:
                area.append(territory.id)
            for tet in territories_lam:
                area_new.append(tet.id)

        print('##################33', len(area))
        print('%%%%%%%%%%%%%%%%%%%%', len(area_new))
        
        print('$$$$$$$$$$$$$$$$$$$', tech_line)
        print('***************8***', al_a6)

this method when executed screen gets loading and I need to optimize this method, please do share your thoughts on how to optimize this code

I cannot limit the value which is generated from the search method as we need all of its value so instead of that I thought to use filtered instead of search method, but when I use filtered it gives an empty recordset. need help with that


Solution

  • You can avoid searching in the for loop by using a search on all users:

    def test(self):
        tech_line = self.env['tech_line']
        tech_lines = tech_line.search(
            [('service_type_id', '=', self.service_type_id.id)])
        # get all users to avoid search in a for loop
        users = tech_lines.mapped("technician_allociated_id.user_id")
        # search territories
        territories = territory.search([('technicians', 'in', users.ids)])
        
        area = territories.ids