Map Odoo records simply

Use Python's defaultdict

Andrius Laukavičius

When you need to map some Odoo records, it can be convenient to use defaultdict from collections module. 

Use case could be: map records by some identifier and then do something with recordset depending on identifier.

Simple Example: map res.partner records by is_company field.

from collections import defaultdict

def map_partners_by_is_company(self, partners):
    """Map partners using is_company field value."""
    # Here factory is function that calls empty recordset for res.partner, so
    # we could use union operation between records.
    partners_map = defaultdict(lambda: self.env['res.partner'])
    for partner in partners:
        partners_map[partner.is_company] |= partner
    return partners_map

partners_map = self.map_partners_by_is_company(partners)
partners_map[True]  # do something with partners that are companies
partners_map[False]  # do something with partners that are individuals.