[FIX] performance: change example with the new _read_group

closes odoo/documentation#6459

Signed-off-by: Antoine Vandevenne (anv) <anv@odoo.com>
This commit is contained in:
Rémy Voet (ryv) 2023-08-18 13:41:04 +02:00
parent 80aa3b74dc
commit 01625aa661

View File

@ -388,23 +388,18 @@ When working with recordsets, it is almost always better to batch operations.
domain = [('related_id', '=', record.id)] domain = [('related_id', '=', record.id)]
record.count = other_model.search_count(domain) record.count = other_model.search_count(domain)
Instead, replace the `search_count` with a `read_group` to execute one SQL query for the entire Instead, replace the `search_count` with a `_read_group` to execute one SQL query for the entire
batch of records. batch of records.
.. rst-class:: good-example .. rst-class:: good-example
.. code-block:: python .. code-block:: python
def _compute_count(self): def _compute_count(self):
if self.ids:
domain = [('related_id', 'in', self.ids)] domain = [('related_id', 'in', self.ids)]
counts_data = other_model.read_group(domain, ['related_id'], ['related_id']) counts_data = other_model._read_group(domain, ['related_id'], ['__count'])
mapped_data = { mapped_data = dict(counts_data)
count['related_id'][0]: count['related_id_count'] for count in counts_data
}
else:
mapped_data = {}
for record in self: for record in self:
record.count = mapped_data.get(record.id, 0) record.count = mapped_data.get(record, 0)
.. note:: .. note::
This example is not optimal nor correct in all cases. It is only a substitute for a This example is not optimal nor correct in all cases. It is only a substitute for a