Skip to Content

Prefetching in Odoo: the same engine, and the habit that breaks it

June 22, 2026 by
Esteban
A report that used to take two seconds started taking forty. The code had barely changed: someone put a .sudo() inside a loop. That small detail switched off the ORM’s prefetching and turned a single query into thousands. 

What prefetching does


When you read a field from a record, Odoo does not read just that field from that record: it reads that field (and the other simple fields) for the whole recordset at once, and caches it. The example in the documentation makes it clear: with a recordset of 1000 partners, reading two fields in a loop would take 2000 queries without prefetching; with prefetching, it takes just one.

partners = env['res.partner'].search([]) # 1000 records


for partner in partners:

print(partner.name) # 1st: brings 'name' (and others) from the 1000 ​ print(partner.lang) # already cached, does not query ​


Consultas SQL para leer 2 campos en 1000 registrosSQL queries to read 2 fields on 1000 records
Sin prefetchWithout prefetch20002,000
Con prefetchWith prefetch1

You don’t have to enable anything. Prefetching is already there whenever you iterate the recordset normally. The problem is breaking it without noticing.

The habit that breaks it

Prefetching lives in the environment cache (env). When you call .sudo(), Odoo gives you the record back in a new environment, and that new environment does not inherit the cache of the previous one. Inside a loop, that means one query per iteration:
​
for partner in partners: 
name = partner.sudo().name # each .sudo() = new query
A thousand records, a thousand queries. Prefetching didn’t fail; you switched it off by asking for a fresh environment on every iteration.

The fix is to move .sudo() outside the loop, just once, so that every read shares the same environment and the same cache:

for partner in partners.sudo():   # a single environment with sudo

name = partner.name           # prefetching is back: one query

Same intention, same sudo, but now it happens once over the whole recordset instead of a thousand times, once per record.

To remember

  • Prefetching is on by default: iterating a recordset reads all its simple fields in one query.
  • .sudo(), with_context() and other environment changes create a new cache.
  •   Do them once on the recordset, never per record inside the loop.
  • In Odoo 18 and 19 the mechanism is the same, so the rule carries over between versions.

References

in Odoo