Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Models and ORM

Recordsets and the Environment

Master Odoo recordsets and the environment: singleton checks, mapped, filtered, sorted, set operations, sudo, with_context and with_company.

In Odoo you almost never handle a single record on its own. The ORM always gives you a recordset: an ordered collection of records of one model, which can hold zero, one or many records. And every recordset carries an environment that says who is calling, in which database transaction and with which context. These two ideas explain most Odoo code you will read.

This lesson shows how recordsets behave, the methods you will use daily (mapped, filtered, sorted), how the environment works and how to change it safely. Code for the real ORM is read-only; the stand-ins at the end build a mini recordset class so the behaviour is visible.

Recordsets everywhere

Inside a model method, self is a recordset. It may contain several records when a user selected many rows in a list and pressed a button:

Python
class LibraryBook(models.Model):
    _inherit = "library.book"

    def action_make_available(self):
        for book in self:                    # iterating yields one-record recordsets
            book.state = "available"

Key facts:

  • Iterating over a recordset gives singletons (recordsets of exactly one record).
  • Field access (book.name) works on a singleton. On a multi-record recordset it raises an error ("Expected singleton"), because the answer would be ambiguous. Use self.ensure_one() at the start of methods that only make sense for one record.
  • An empty recordset is falsy: if not books: tests for no result.
  • Assigning to a field on a recordset writes it for all records at once: self.state = "lost" is a single write, which is faster than looping.
  • Relational fields return recordsets too: order.partner_id is a one-record recordset of res.partner; order.order_line is a recordset of lines.

Handy recordset methods

Python
books = env["library.book"].search([("state", "=", "available")])

books.mapped("name")                    # list of names
books.mapped("loan_ids")                # recordset: all loans of all books (flattened, no duplicates)
books.mapped("loan_ids.member_id.name") # follow a path of fields

books.filtered(lambda b: b.pages > 300)     # records where the function is true
books.filtered("published")                 # or by a field name (true values only)

books.sorted(key=lambda b: b.pages, reverse=True)
books.sorted("name")                        # sort by field names

len(books), books.ids, books[0], books[:5]  # size, ids, indexing, slicing
books | other_books                         # union
books & other_books                         # intersection
books - other_books                         # difference

mapped, filtered and sorted work in Python on records already loaded. For large tables, prefer filtering in the database through a domain in search() (next lesson), and use filtered on the small result.

The environment

Every recordset has self.env, an Environment object, which holds:

  • env.cr: the database cursor (the transaction).
  • env.uid: the id of the current user, and env.user as a record.
  • env.context: a read-only dictionary of extra information such as language, time zone and default values.
  • env.company and env.companies: the current and allowed companies.
  • env["res.partner"]: access to any model's empty recordset, the way you start searches.
  • env.ref("module.xml_id"): fetch a record by external id.

Changing the environment never mutates the old one; instead you get a new recordset of the same records with a different environment:

Python
book.with_context(lang="fr_FR").name       # read translatable terms in French
book.sudo().write({"state": "lost"})       # run as the superuser, bypass access rules
book.with_user(other_user).read(["name"])  # run as another user
book.with_company(company_b)               # switch the current company
book.with_env(new_env)                     # rarely needed

Be careful with sudo(): it skips all access rights and record rules. Use it for narrow, deliberate jobs (a portal user triggering a protected update) and never as a general fix for "access denied". Chapter 6 comes back to this.

The context is also how defaults travel: the key default_<field> pre-fills a new record, as in with_context(default_species="cat").create({...}).

Caching and transactions

The ORM keeps a cache per environment, so reading book.name twice runs SQL once. Writes are held in a transaction and committed when the request ends successfully; an exception raised in your method rolls everything back. You should almost never call self.env.cr.commit() yourself: it breaks the all-or-nothing guarantee. The exceptions are long batch jobs that commit in chunks on purpose.

A runnable stand-in: a tiny recordset

The stand-in below implements __iter__, truthiness, mapped, filtered, sorted, set operations and ensure_one on a toy class. Run it and compare with the descriptions above.

Python Stand-in: a mini recordset

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: an environment that changes the context

with_context returns a new object; the original stays unchanged. This stand-in makes that visible with an immutable environment.

Python Stand-in: with_context makes a new environment

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 happens when you read book.name on a recordset that holds three books?

    Field access needs exactly one record. Use mapped('name') for several or iterate.
  2. 2. What does recordset.mapped('partner_id.name') return?

    When the final field is not relational, mapped returns a plain list of values.
  3. 3. What does sudo() do?

    sudo() uses the superuser environment. It is powerful and must be used deliberately.
  4. 4. How do you pre-fill the field species with 'cat' when creating a record through the ORM?

    Keys named default_<field> in the context supply default values for new records.

Summary

  • ORM methods return recordsets; iterating gives one-record recordsets, and field access needs a singleton.
  • mapped, filtered, sorted and the set operators |, &, - work on loaded records.
  • The environment holds cursor, user, context and company, and is immutable: with_context, with_user, sudo and with_company return new recordsets.
  • Empty recordsets are falsy; assigning to a field writes all records at once.
  • Do not commit manually; an exception rolls the transaction back.

Next: Searching and CRUD with Domains