Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Models and ORM

Computed Fields, Onchange and Constraints

Add logic to Odoo models: computed fields with @api.depends, stored versus non-stored, onchange helpers and validation with @api.constrains.

Plain fields store what users type. Real applications also need values that follow from other values (an order total), helpers that react while the user is editing (fill the price after choosing a product) and rules that reject bad data (the end date cannot be before the start date). Odoo has one tool for each: computed fields, onchange methods and constraints.

This lesson explains all three with real Odoo code (read-only) and Python stand-ins that reproduce the dependency tracking and validation logic.

Computed fields

A computed field gets its value from a method rather than from user input:

Python
from odoo import api, fields, models


class LibraryLoan(models.Model):
    _name = "library.loan"
    _description = "Loan"

    date_out = fields.Date(required=True, default=fields.Date.today)
    date_due = fields.Date(required=True)
    duration = fields.Integer(compute="_compute_duration", store=True)
    is_late = fields.Boolean(compute="_compute_is_late")

    @api.depends("date_out", "date_due")
    def _compute_duration(self):
        for loan in self:
            if loan.date_out and loan.date_due:
                loan.duration = (loan.date_due - loan.date_out).days
            else:
                loan.duration = 0

    @api.depends("date_due")
    def _compute_is_late(self):
        today = fields.Date.today()
        for loan in self:
            loan.is_late = bool(loan.date_due and loan.date_due < today)

The rules of a compute method:

  1. It must assign a value to the field for every record in self, including the case where inputs are empty. Forgetting a branch raises an error.
  2. It loops over self (a recordset, possibly many records).
  3. @api.depends(...) lists the fields the result relies on, including dotted paths such as "line_ids.price_subtotal". When one of them changes, Odoo knows the field is out of date and recomputes it. A missing dependency means stale values, the most common bug.

Stored or not?

  • Not stored (the default): the value is computed when read and kept in the cache; nothing is in the database. Cheap to keep correct, but you cannot easily search or sort on it unless you also provide a search method.
  • store=True: the value is saved in a column and recomputed when dependencies change. You can search, sort and group on it, at the price of recomputation work on writes. Use it for values used in filters, reports and pivots.

Do not use store=True for something that depends on the current date or user (like is_late above): the stored value would age without any dependency change to trigger an update.

To let users edit a computed field, add an inverse method that writes the change back to the sources. To allow searching a non-stored computed field, add a search method that returns a domain on stored fields.

Python
is_late = fields.Boolean(compute="_compute_is_late", search="_search_is_late")

def _search_is_late(self, operator, value):
    if operator != "=":
        raise NotImplementedError("only = is supported")
    today = fields.Date.today()
    return [("date_due", "<" if value else ">=", today)]

Onchange

An onchange method runs in the form while the user edits, before saving. It can change other fields in the form and show a warning:

Python
@api.onchange("book_id")
def _onchange_book_id(self):
    if self.book_id:
        self.date_due = fields.Date.add(fields.Date.today(), days=14)
        if self.book_id.state != "available":
            return {"warning": {"title": "Book not available",
                                "message": "This book is not on the shelf."}}

Remember what an onchange is not: it runs only in the web client form, not when records are created by code, imports or the external API. Business rules that must always hold belong in constraints or in compute methods; onchange is a convenience for the interface. For defaulting a value from another field consider a computed field with store=True, readonly=False, precompute=True instead, which works for code as well as the UI.

Constraints

A Python constraint is checked whenever the listed fields are written or created, whatever the entry point:

Python
from odoo.exceptions import ValidationError

@api.constrains("date_out", "date_due")
def _check_dates(self):
    for loan in self:
        if loan.date_due and loan.date_out and loan.date_due < loan.date_out:
            raise ValidationError("The due date cannot be before the loan date.")

Use ValidationError for data that must be refused (it rolls back the transaction and shows the message) and UserError for other blocking messages in actions. SQL constraints (_sql_constraints and unique/check rules) are enforced by PostgreSQL, so they are the right choice for uniqueness, where races between users matter.

Tool Runs when Use for
Computed field Value is read or dependencies change Derived values
@api.onchange User edits a form (UI only) Suggestions, warnings
@api.constrains Fields are written (any way) Python validation
SQL constraint Database insert or update Uniqueness, simple checks

A runnable stand-in: dependency tracking

This stand-in recomputes a stored total only when one of its declared dependencies is written. It prints each recomputation so you can see the effect of @api.depends, and shows the bug caused by a forgotten dependency.

Python Stand-in: @api.depends in plain Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fix the stand-in by adding "discount" to the dependency set and run it again: the stale value disappears. That is exactly the bug you get in Odoo with an incomplete @api.depends.

A second stand-in: constraints reject bad data

Constraints must hold on every entry point. This stand-in applies two validators when a record is written, whether by "form" or "import".

Python Stand-in: validation on every write

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a compute method do for every record in self?

    Every record needs a value assigned, even in the branch where the inputs are empty.
  2. 2. A stored computed field shows an old value after a related field changed. What is the likely cause?

    Odoo only recomputes when a declared dependency changes.
  3. 3. Why is @api.onchange not enough to enforce a business rule?

    Use constraints or computed fields for rules that must always hold.
  4. 4. Which is best for guaranteeing a unique ISBN even with concurrent users?

    The database enforces SQL constraints atomically, which avoids race conditions.

Summary

  • Computed fields derive values; list every input in @api.depends and assign a value for every record.
  • store=True allows searching and grouping but costs recomputation; avoid it for date- or user-dependent values.
  • inverse makes a computed field editable; search makes a non-stored one searchable.
  • Onchange methods help in the form only; never rely on them for rules.
  • @api.constrains and SQL constraints validate data whatever the entry point.

Next: Model Inheritance