Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Models and ORM

Relational Fields

Link Odoo models with Many2one, One2many and Many2many fields: storage, ondelete, domains, related fields and the create/write command tuples.

Business data is a web of relations: an order belongs to a customer, has many lines, and each line refers to a product that can carry several tags. Odoo models these links with three relational field types. Choosing the right one and knowing how it is stored saves you from many design mistakes.

This lesson covers Many2one, One2many, Many2many, related fields and the special commands used to change x2many fields. As before, the Odoo code is read-only and the runnable examples are Python and SQLite stand-ins.

Many2one: the foreign key

A Many2one points from this record to one record of another model. It is stored as a column holding the id of the target (a foreign key).

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

    book_id = fields.Many2one(
        "library.book",
        string="Book",
        required=True,
        ondelete="restrict",
        domain=[("state", "=", "available")],
    )
    member_id = fields.Many2one("res.partner", string="Member", ondelete="cascade")

Important options:

  • ondelete: what happens to this record when the target is deleted. "set null" (the default for optional fields) empties the field; "restrict" refuses the deletion; "cascade" deletes this record too.
  • domain: limits the choices in the drop-down. A list of conditions in the domain syntax.
  • context: values passed to the target form or search (for example default values).
  • check_company=True: in multi-company databases, refuse targets of another company.
  • index=True: Many2one columns used for searching should be indexed.

One2many: the reverse list

A One2many shows all records of another model that point back to this one through a Many2one. It stores nothing in this table; the data lives in the other model's Many2one column, which you name as the second argument.

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

    loan_ids = fields.One2many("library.loan", "book_id", string="Loans")

"book_id" must be a Many2one on library.loan pointing to library.book. In forms a One2many is shown as an editable list, for example the order lines inside a quotation.

Many2many: both sides many

A Many2many relates records on both sides: a book has many tags, and a tag marks many books. PostgreSQL needs a relation table with two columns, which Odoo creates automatically and names after the two models.

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

    tag_ids = fields.Many2many("library.tag", string="Tags")
    # explicit relation table if you need control:
    # fields.Many2many("library.tag", "book_tag_rel", "book_id", "tag_id")
erDiagram
    LIBRARY_BOOK ||--o{ LIBRARY_LOAN : "book_id (Many2one)"
    LIBRARY_BOOK }o--o{ LIBRARY_TAG : "book_tag_rel (Many2many)"
    LIBRARY_LOAN }o--|| RES_PARTNER : "member_id (Many2one)"

Only Many2one stores a foreign key; One2many is the other end of it, and Many2many uses a join table.

A related field copies a value across a relation, so you can show or search it without duplicating logic:

Python
member_email = fields.Char(related="member_id.email", string="Member email", store=False)

By default a related field is computed and not stored; add store=True to save it (useful for searching and grouping, at the price of updates). It is read-only unless you set readonly=False.

Commands for x2many fields

When you write to a One2many or Many2many through create() or write(), you pass a list of commands. Each command is a tuple, and recent series offer the readable Command helper:

Command Tuple Effect
Create (0, 0, values) or Command.create(values) Create a linked record
Update (1, id, values) or Command.update(id, values) Write on a linked record
Delete (2, id) or Command.delete(id) Delete the linked record
Unlink (3, id) or Command.unlink(id) Remove the link, keep the record
Link (4, id) or Command.link(id) Add a link to an existing record
Clear (5,) or Command.clear() Remove all links
Set (6, 0, ids) or Command.set(ids) Replace all links with these ids
Python
from odoo import Command

book.write({
    "tag_ids": [Command.link(tag_scifi.id), Command.link(tag_classic.id)],
    "loan_ids": [Command.create({"member_id": partner.id})],
})

The two codes that cause most confusion are Unlink (3), which only cuts the link, and Delete (2), which also removes the record. For a One2many, unlinking a line sets its Many2one to empty, which fails if the field is required.

Choosing the field type

  • "Each loan has one book" โ†’ Many2one on loan.
  • "A book shows all its loans" โ†’ One2many on book (plus the Many2one above).
  • "Tags on books" โ†’ Many2many, unless the link carries data of its own (date, quantity). Then create a separate link model with two Many2ones, as order lines do.

A runnable stand-in: how relations are stored

SQLite is enough to show how the three types look in tables: a foreign-key column, the reverse side that needs no storage and a relation table.

Python Stand-in: Many2one, One2many and Many2many tables

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: command tuples

This Python function applies the command codes to a list of ids, the way the ORM does for a Many2many field.

Python Stand-in: apply x2many commands

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. Where does a Many2one field store its data?

    A Many2one is a column with the target record's id.
  2. 2. What does a One2many field need as its second argument?

    The One2many reads the records of the other model whose Many2one points to this record.
  3. 3. Which command removes the link but keeps the linked record?

    (3, id) unlinks; (2, id) deletes the record as well.
  4. 4. When would you create a link model instead of a Many2many?

    A plain Many2many has no extra columns. Order lines are a link model between orders and products.

Summary

  • Many2one is a foreign key column; set ondelete, domain and index thoughtfully.
  • One2many is the reverse view of a Many2one and stores nothing itself.
  • Many2many uses an automatically created relation table.
  • Related fields read through a relation; store=True makes them searchable but costs updates.
  • Create, update, delete, link, unlink, clear and set commands change x2many fields.

Next: Recordsets and the Environment