To write a method that returns a dictionary that contains the mapped names of countries to a recordset of all active partners from that country, you need to perform the following steps:
- Write a class extending res.partner:
class ResPartner(models.Model): _inherit = 'res.partner'
- Add a method called partners_by_country():
@api.model def partners_by_country(self):
- In the method, write the following SQL query:
sql = ('SELECT country_id, array_agg(id) ' 'FROM res_partner ' 'WHERE active=true AND country_id IS NOT NULL ' 'GROUP BY country_id')
- Execute the query:
self.env.cr.execute(sql)
- Iterate over the results of the query to populate the result dictionary:
country_model = self.env['res.country'] result = {} for country_id, partner_ids in self.env.cr.fetchall(): country = country_model.browse(country_id) partners = self.search( [('id', 'in', tuple(partner_ids))] ) result[country] = partners return result