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
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
for partner in partners:
name = partner.sudo().name # each .sudo() = new query
for partner in partners.sudo(): # a single environment with sudo
name = partner.name # prefetching is back: one query
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.