How to do it...

The read_group() method is widely used for statistics and smart stat buttons. Let's assume you want to show the number of sales orders on the partner form. This can be done by searching sales orders for a customer and then counting the length:

# in res.partner model
so_count = fields.Integer(compute='_compute_so_count', string='Sale order count')

def _compute_so_count(self):
sale_orders = self.env['sale.order'].search(domain=[('partner_id', 'in', self.ids)])
for partner in self:
partner.so_count = len(sale_orders.filtered(lambda so: so.partner_id.id == partner.id))

This example will work, but it is not optimized. When you display the so_count field on the tree view, it will fetch and filter sales orders for all the partners in a list. With this small amount of data, the read_group() method won't make much difference, but as the amount of data grows, it could be a problem. To fix this issue, you can use the read_group method. The following example will do the same as the preceding one, but it only consumes one SQL query, even for large datasets:

# in res.partner model
so_count = fields.Integer(compute='_compute_so_count', string='Sale order count')

def _compute_so_count(self):
sale_data = self.env['sale.order'].read_group(
domain=[('partner_id', 'in', self.ids)],
fields=['partner_id'], groupby=['partner_id'])
mapped_data = dict([(m['partner_id'][0], m['partner_id_count']) for m in sale_data])
for partner in self:
partner.so_count = mapped_data[partner.id]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset