Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Models and ORM

Searching and CRUD with Domains

Create, read, update and delete records in the Odoo ORM and write search domains with operators, prefix logic, limit, order and search_count.

Now that you know models and recordsets, let's put data in and get it out. The Odoo ORM offers a small, consistent set of methods for CRUD (create, read, update, delete) and a mini query language called domains to say which records you want. The same domains appear in Python code, in view filters, in access rules and in automated actions, so learning them well pays off everywhere.

The ORM code in this lesson is read-only. The runnable stand-ins implement a small domain engine in Python so you can experiment with the logic, including the tricky prefix operators.

Python
Book = env["library.book"]

# create: one dictionary, or a list of dictionaries (faster for many records)
dune = Book.create({"name": "Dune", "pages": 412})
many = Book.create([{"name": "Emma"}, {"name": "Ulysses", "pages": 730}])

# write: update all records of the recordset with one call
dune.write({"state": "available", "pages": 420})
dune.pages = 421              # attribute assignment also writes

# unlink: delete (the Python method name for deletion)
many[0].unlink()

# copy: duplicate (fields with copy=False are skipped)
copy = dune.copy({"name": "Dune (2nd copy)"})

create returns the new recordset, write returns True and unlink removes rows (and cascades or restricts according to the ondelete of related fields). All three respect access rights and record rules of the current user.

Search and browse

Python
available = Book.search([("state", "=", "available")], order="name", limit=20, offset=0)
one = Book.search([("isbn", "=", "9780441172719")], limit=1)   # may be empty!
total = Book.search_count([("state", "=", "available")])
by_id = Book.browse(7)                  # a recordset for id 7 (no SQL until you read a field)
by_ids = Book.browse([1, 2, 3])

search returns a recordset. Remember that empty is a valid result: always handle the case where nothing matches. browse does not check that the id exists; if it does not, a later read raises a MissingError. search_count is much cheaper than len(search(...)) when you only need the number.

read(["name", "pages"]) returns a list of dictionaries instead of records, and search_read(domain, fields) combines both; they are used mainly by the web client and external API callers.

Domains

A domain is a list. Each condition is a tuple (field, operator, value):

Python
[("state", "=", "available"), ("pages", ">", 300)]    # AND by default

Common operators:

Operator Meaning
=, != Equal, different
>, >=, <, <= Comparison
like, ilike Pattern match with %; ilike ignores case
=like, =ilike Exact pattern, you supply the % signs
in, not in Value in a list: ("state", "in", ["draft", "lost"])
child_of, parent_of Hierarchy (categories, companies)
=? Equal, but the condition is ignored if the value is False/None

You can follow relations with dotted paths: ("loan_ids.member_id.name", "ilike", "ann") finds books lent to a member whose name contains "ann". Recent series also provide an any operator with a sub-domain for a one-to-many field: ("loan_ids", "any", [("returned", "=", False)]).

Prefix logic: &, | and !

Conditions in a list are joined by AND. For OR and NOT you put an operator before its operands (Polish or prefix notation):

Python
# state is draft OR state is lost
["|", ("state", "=", "draft"), ("state", "=", "lost")]

# (draft OR lost) AND pages > 100
["|", ("state", "=", "draft"), ("state", "=", "lost"), ("pages", ">", 100)]

# NOT available
["!", ("state", "=", "available")]

"|" and "&" each take the next two expressions; "!" takes the next one. The implicit AND between top-level terms is what makes the third example work: the "|" consumes the first two conditions, then ("pages", ">", 100) is ANDed. Forgetting that | needs exactly two operands is the classic domain bug; for three alternatives write ["|", "|", a, b, c].

flowchart TB
    AND(("AND (implicit)")) --> OR(("|"))
    AND --> P["pages > 100"]
    OR --> D["state = draft"]
    OR --> L["state = lost"]

The domain ["|", draft, lost, pages>100] as a tree: the OR consumes the two conditions that follow it.

Grouped reads

For totals per group (the kind of data behind pivot tables and graphs) the ORM offers read_group (and in newer series _read_group and formatted_read_group). A typical call groups loans by member and counts them. The exact name and return shape vary by series, so look at the source of your version before using it in code; the stand-in below shows the idea.

Errors you will meet

  • AccessError: your user lacks a right or a record rule blocks the record.
  • MissingError: the record was deleted between loading and use.
  • ValidationError and UserError: raised by your own code or constraints to show a message to the user.
  • ValueError: Expected singleton: you read a field on a multi-record recordset.

A runnable stand-in: a domain evaluator

This stand-in evaluates a prefix-notation domain with a simple stack-free recursive parser. It supports =, !=, comparisons, in, ilike and the three logical operators. It is far smaller than Odoo's real implementation, but the prefix logic is identical.

Python Stand-in: evaluate domains with &, | and !

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.

A second stand-in: search with order, limit and count

Combining a domain with order, limit and offset gives paging, which is what list views use.

Python Stand-in: order, limit, offset and count

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. How are the conditions in [('a', '=', 1), ('b', '=', 2)] combined?

    Terms at the top level of a domain are joined by an implicit AND.
  2. 2. How many operands does the | operator take in a domain?

    | and & each take the next two expressions. For three alternatives write two | operators.
  3. 3. Which call is best when you only need to know how many records match?

    search_count runs a COUNT query without loading records.
  4. 4. What does Model.browse(42) do if no record with id 42 exists?

    browse builds a recordset from ids without checking the database.

Summary

  • create, write, unlink, copy change data; search, search_count, browse, read and search_read fetch it.
  • A domain is a list of (field, operator, value) terms joined by implicit AND, with prefix &, | and !.
  • Use dotted paths to search through relations; ilike for case-insensitive matches, in for lists.
  • search may return an empty recordset, and browse does not check ids.
  • Use limit, offset, order for paging and search_count for counting.

Next: Computed Fields, Onchange and Constraints