How to Implement precompute=True in Odoo?
What is precompute=True?
In Odoo, precompute=True is a field-level attribute used with compute fields. When set, it instructs the ORM to compute the field's value as early as possible, before the record is fully created and stored in the database.
This is useful when the computed value is required during or immediately after the creation of a record — for example, when another dependent compute or constraint relies on this field.
✅ Where to Use
Used in computed fields:
my_field = fields.Char(compute='_compute_my_field', precompute=True, store=True)
- Works only if store=True is also set.
- The compute method must not depend on self.id or fields that are not yet assigned.
🔍 Behavior
- With precompute=True: The computed field is evaluated before the record is saved.
- Without precompute=True: The field is computed only after the record is stored and committed.
📌 Realistic Use Case in Odoo
🔸 Example: Automatically Set a Reference Code on Record Creation
class MyModel(models.Model):
_name = 'my.model'
name = fields.Char(string='Name')
reference = fields.Char(compute='_compute_reference', store=True, precompute=True)
@api.depends('name')
def _compute_reference(self):
for rec in self:
rec.reference = f"REF-{rec.name or ''}".upper()
With precompute=True, the reference field will be available immediately upon record creation, even in create() method logic or for SQL constraints.
Why It Matters
- Used in computed defaults required at creation time.
- Avoids race conditions or missing values in constraints.
- Ensures dependent fields or logic relying on the computed field work without delays.
⚠️ Important Notes
- Should be used only when the compute method does not rely on id, create_date, or other values that are only set after the record is saved.
- Use only when early access to the value is truly required.
✅ Summary Table
Parameter | Purpose | When to Use |
precompute=True | Precomputes field before record is saved | When field is needed early (e.g., for constraints or other compute logic) |
Must be store=True | Required to be a stored field | Only works with stored computed fields |