How to Implement prefetch_fields Optimization in Modern Odoo (v15+ and above) ?


✅ What is prefetch_fields?

In Odoo, the ORM preloads fields to reduce queries during recordset access. However, in large datasets or performance-critical tasks, this can cause unnecessary memory usage or slower performance.

To control this behavior, Odoo supports disabling or customizing prefetching via:

self.with_context(prefetch_fields=False)


📌 Realistic Odoo Examples


1. Disable Prefetching Entirely


partners = self.env['res.partner'].with_context(prefetch_fields=False).search([('is_company', '=', True)])

for rec in partners:

    logger.info(rec.id)

  • This disables automatic field loading.
  • Only rec.id is fetched from the DB unless other fields are explicitly accessed.
  • Suitable for large recordsets where only a few fields are needed.


  • 2. Prefetch Only Specific Fields

partners = self.env['res.partner'].with_context(prefetch_fields=['id', 'name']).search([('is_company', '=', True)])

for rec in partners:

    logger.info(rec.name)


  • Only the listed fields (id, name) are preloaded.
  • Improves performance when full field data is not required.


🧠 When to Use


Scenario

Use prefetch_fields?

Background jobs or scripts processing 10k+ records

✅ Yes — optimize memory and I/O

API endpoints returning minimal data

✅ Yes — restrict to needed fields

Accessing computed/image/relational fields

❌ No — allow prefetch to avoid repeated queries

Regular UI and business logic

❌ Not necessary


⚠️ Common Mistake


# ❌ Deprecated in newer versions:

self.with_prefetch_fields(False)

  • Replaced with with_context(prefetch_fields=False) in newer versions like Odoo 15+.


✅ Summary Table


Context Code

Behavior

with_context(prefetch_fields=False)

No prefetching — fetch only when needed

with_context(prefetch_fields=['id', 'name'])

Only prefetch specified fields

No context

Default ORM prefetches most fields