Technical
Odoo ORM Performance: Prefetching, read_group and N+1 Fixes
A practical guide for Odoo developers: how prefetching works, when to use read_group, how to remove N+1 queries from computed fields, how to batch create and write, and how to profile a slow view.
Kalvyai Engineering · · Updated · 6 min read

On this page
Most slow Odoo screens are not slow because of PostgreSQL or the server size. They are slow because custom code sends hundreds of small queries where a few would do. This post covers the ORM habits that fix most of these cases, with short examples you can apply to your own modules.
Code examples target Odoo 17 unless noted. Where APIs differ in older versions, we say so.
How prefetching works, and how to break it by accident
When you read a field on one record in a recordset, the ORM does not fetch just that one value. It fetches the field (and other prefetchable stored fields of the same model) for all records in the record's prefetch set, in batches. Iterating over a recordset of 500 orders and reading amount_total costs a handful of queries, not 500.
The prefetch set comes from the recordset the record was taken from. If you build records one at a time, each one gets a prefetch set of one, and you are back to one query per record.
# Slow: each browse() creates a new prefetch set with a single record
total = 0
for order_id in order_ids:
order = self.env['sale.order'].browse(order_id)
total += order.amount_total
# Fast: one recordset, the field is fetched for all records together
orders = self.env['sale.order'].browse(order_ids)
total = sum(orders.mapped('amount_total'))The same applies to relational fields. orders.partner_id.country_id reads partners for all orders, then countries for all those partners, in a few queries.
Common ways prefetching gets lost
- Calling
browse()orsearch()inside a loop for one record at a time. - Passing lists of ids between methods and browsing them again record by record.
- Calling
sudo()orwith_context()on each record inside the loop. Do it once on the whole recordset before the loop. - Running a
search()per record to find related data. That is the classic N+1, covered next.
Removing N+1 queries from computed fields
A compute method receives a recordset in self, often many records at once (for example, every row on a list view page). Code that runs a query inside for record in self runs that query once per row.
Here is a typical slow version: a count of open customer invoices per partner.
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
open_invoice_count = fields.Integer(compute='_compute_open_invoice_count')
def _compute_open_invoice_count(self):
# Slow: one search_count per partner
for partner in self:
partner.open_invoice_count = self.env['account.move'].search_count([
('partner_id', '=', partner.id),
('move_type', '=', 'out_invoice'),
('state', '=', 'posted'),
('payment_state', 'not in', ('paid', 'in_payment', 'reversed')),
])On a list of 80 partners this is 80 queries. The fix is to ask once for all partners, then distribute the results in Python.
def _compute_open_invoice_count(self):
groups = self.env['account.move']._read_group(
domain=[
('partner_id', 'in', self._origin.ids),
('move_type', '=', 'out_invoice'),
('state', '=', 'posted'),
('payment_state', 'not in', ('paid', 'in_payment', 'reversed')),
],
groupby=['partner_id'],
aggregates=['__count'],
)
counts = {partner.id: count for partner, count in groups}
for partner in self:
partner.open_invoice_count = counts.get(partner._origin.id, 0)One query, regardless of how many partners are on screen. Using _origin keeps the method safe in forms, where records can be new (unsaved) and do not have a real database id yet.
The domain above is an example. Adjust it to your business rule, for example if invoices are linked to child contacts rather than the commercial partner.
Stored or not stored
Non-stored computed fields are recomputed every time they are displayed. If a field is shown on large list views, used in search filters, sorted or grouped on, consider store=True with a correct @api.depends. The trade-off is that writes to the dependencies trigger recomputation, so a stored field with broad dependencies can slow down writes instead. Measure both sides.
Using read_group for aggregates
Any time you loop over records to sum, count or average, check whether the database can do it. _read_group runs a single GROUP BY query.
In Odoo 17 and later, _read_group takes a domain, a list of group-by fields and a list of aggregates, and returns tuples. Many2one group values come back as records.
# Total untaxed amount per sale order, in one query
rows = self.env['sale.order.line']._read_group(
domain=[('order_id', 'in', orders.ids)],
groupby=['order_id'],
aggregates=['price_subtotal:sum'],
)
totals = {order.id: subtotal for order, subtotal in rows}
# Count of confirmed orders per month
rows = self.env['sale.order']._read_group(
domain=[('state', '=', 'sale')],
groupby=['date_order:month'],
aggregates=['__count'],
)In Odoo 16 and earlier, the server-side call is read_group(domain, fields, groupby) and it returns dictionaries. Many2one values are (id, display_name) pairs, and counts use a <field>_count key:
# Odoo 16 and earlier
groups = self.env['account.move'].read_group(
domain, ['partner_id'], ['partner_id'],
)
counts = {g['partner_id'][0]: g['partner_id_count'] for g in groups}The public read_group API has changed again in recent versions. Since Odoo Online 18.2 (and so in Odoo 19), public read_group is deprecated in favor of _read_group for backend code and formatted_read_group as the formatted public API. For server-side code in 17+, _read_group is the method to use.
Note that _read_group aggregates at SQL level, so it only works on stored fields. If you need to aggregate a non-stored computed field, either store it or aggregate its stored inputs.
Batch create and write
Create many records in one call
create() accepts a list of value dictionaries. Passing the whole list lets the ORM insert in batches and run compute and constraint logic once per batch instead of once per record.
# Slow
for row in rows:
self.env['product.supplierinfo'].create(row)
# Fast
self.env['product.supplierinfo'].create(rows)If you override create, keep it batch-friendly with @api.model_create_multi and handle the list:
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
vals.setdefault('reference', self._default_reference())
records = super().create(vals_list)
records._sync_after_create() # operate on the whole recordset
return recordsAvoid calling a single-record helper for each new record at the end of create. That reintroduces the loop you just removed.
For large imports on models that inherit mail.thread, chatter tracking and creation messages add queries per record. The context keys tracking_disable, mail_create_nolog and mail_notrack reduce that work. Only use them when you do not need the chatter history for those records.
Write the same values once
write() on a recordset with one set of values updates all records together. If different records need different values, group them by value first:
from collections import defaultdict
ids_by_categ = defaultdict(list)
for tmpl in templates:
ids_by_categ[self._pick_category(tmpl)].append(tmpl.id)
Product = self.env['product.template']
for categ_id, ids in ids_by_categ.items():
Product.browse(ids).write({'categ_id': categ_id})This turns thousands of writes into one write per distinct value.
Chunk very large jobs
For scheduled jobs that touch hundreds of thousands of records, process in chunks so memory and transaction size stay under control. odoo.tools.split_every helps:
from odoo.tools import split_every
for chunk_ids in split_every(1000, all_ids):
records = self.env['my.model'].browse(chunk_ids)
records._process()
self.env.invalidate_all() # Odoo 16+: release the cache between chunksIn Odoo 15 and earlier, the cache method is invalidate_cache(). Committing between chunks is sometimes done in cron jobs, but it changes error handling (a failure no longer rolls back earlier chunks), so decide on it deliberately.
Profiling a slow view
Guessing is expensive. Measure first, change one thing, measure again.
1. Log the SQL
Start Odoo with SQL logging on a development copy:
./odoo-bin -c odoo.conf --log-handler=odoo.sql_db:DEBUGOpen the slow view and read the log. You are looking for the same query shape repeated many times with only the id changing. That pattern points straight at an N+1 loop.
2. Use the built-in profiler
Odoo 15 and later include a profiler that records SQL queries and Python stack traces for a request, and shows them as a flame graph. In developer mode, it is enabled from the debug menu in the top bar. To profile your session, toggle the Enable profiling button in the developer mode tools; saved profiles are listed as ir.profile records grouped by profiling session, opened from the button in the top-right corner of the profiling section of the developer mode tools. Profiling also has to be allowed on the database by an administrator. Go to Settings → General Settings → Performance and set the Enable profiling until field (or use the Enable profiling wizard in the developer mode tools).
The flame graph shows which Python method spends the time and how many queries it triggers. Compute methods and _search overrides often stand out.
3. Lock it in with a test
Once fixed, keep it fixed. assertQueryCount fails the test if the number of queries changes:
from odoo.tests.common import TransactionCase
class TestPartnerPerformance(TransactionCase):
def test_open_invoice_count_is_batched(self):
partners = self.env['res.partner'].create(
[{'name': f'Partner {i}'} for i in range(50)]
)
partners.invalidate_recordset() # Odoo 16+
# Set the number to what you measure; it must not grow with record count
with self.assertQueryCount(2):
partners.mapped('open_invoice_count')Run it with 5 records and with 50. If the count is the same, the compute is batched.
4. Check the database side
If one query is slow on its own (rather than many fast queries), run it with EXPLAIN ANALYZE in psql:
EXPLAIN ANALYZE
SELECT id FROM account_move
WHERE partner_id IN (1, 2, 3)
AND move_type = 'out_invoice'
AND state = 'posted';A sequential scan on a large table usually means a missing index. Add index=True on fields you filter or sort on often. Odoo 16+ also accepts index types such as 'btree_not_null' and 'trigram' for specific cases.
What usually makes a list view slow
- Non-stored computed fields with a query per record.
- Related fields that walk through several models.
- A default
_orderon a non-indexed field. - Record rules with complex domains that make every query heavier.
- Many2many tag columns on models with many rows.
Quick checklist
- No
search(),search_count()orbrowse()of single ids inside loops. - Compute methods work on all of
selfwith one query per related model. - Sums and counts use
_read_group(orread_groupon 16 and earlier). create()gets a list; overrides use@api.model_create_multi.write()is called once per distinct set of values.- Large jobs run in chunks with the cache cleared between them.
- Performance-critical paths have an
assertQueryCounttest.
How Kalvyai can help
We build and maintain custom Odoo modules, and a good part of that work is finding and removing slow ORM patterns in existing code: profiling the views users complain about, batching compute methods, adding the right indexes, and adding tests so the fix stays in place. You can see more about our Odoo work at https://kalvyai.com/odoo, and the modules we publish are at https://store.kalvyai.com.
If you have an Odoo screen that takes too long to load, or a cron job that runs for hours, contact us with the version and a short description, and we will tell you where we would start.
Last updated 20 Nov 2026
- Odoo
- ORM
- Performance
- Python
- PostgreSQL
- Profiling
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment