Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Models and ORM

Model Inheritance

Extend Odoo models without touching core code: _inherit, prototype copies, _inherits delegation, abstract mixins and overriding methods with super().

The rule that keeps Odoo upgradable is simple: never edit a core module, extend it. Inheritance is the mechanism. With a few lines you can add a field to res.partner, change what sale.order.action_confirm does, or create a new model that reuses all the behaviour of an existing one. Odoo offers three inheritance styles, and choosing the right one is part of good design.

This is the last lesson of the models chapter and it ties everything together: model registry, fields, methods and the super() call. Real Odoo code is read-only; the stand-ins at the end recreate how several modules can contribute to a single final class.

1. Classical extension: _inherit without _name

Use _inherit on its own to add to an existing model in place. No new table is created; the same model gains fields and methods, for every module that is installed.

Python
from odoo import fields, models


class ResPartner(models.Model):
    _inherit = "res.partner"

    loyalty_level = fields.Selection(
        [("none", "None"), ("silver", "Silver"), ("gold", "Gold")],
        default="none",
    )
    pet_ids = fields.One2many("vet.pet", "owner_id", string="Pets")

After installing the module the column loyalty_level exists in res_partner and the field is available in every app, including the web forms where you add it to a view. This is by far the most common pattern.

2. Overriding methods and super()

You can also replace or extend methods. When you redefine a method with the same name in an inheriting class, your version runs first, and super() calls the version defined by earlier modules in the chain:

Python
from odoo import models
from odoo.exceptions import UserError


class SaleOrder(models.Model):
    _inherit = "sale.order"

    def action_confirm(self):
        for order in self:
            if order.partner_id.loyalty_level == "none" and order.amount_total > 10000:
                raise UserError("Large orders need a loyalty level.")
        result = super().action_confirm()      # standard behaviour
        self._notify_sales_team()              # your addition, after the standard steps
        return result

    def _notify_sales_team(self):
        for order in self:
            order.message_post(body="Order confirmed.")

Guidelines for overrides:

  • Always call super() unless you really want to replace the behaviour, because other modules may also extend the method. A missing super() silently disables their code.
  • Return what super() returns.
  • Put your checks before super() to stop early, and your extras after it to act on the finished result.
  • Keep the same signature, including *args, **kwargs when the parent uses them.

The order of the chain follows the module load order (the dependency graph from chapter 3). A module loaded later wraps those loaded earlier, so its code runs first and super() descends.

3. Prototype inheritance: _inherit with a new _name

Giving both _inherit and a different _name copies the parent's fields and methods into a new model with its own table:

Python
class LibraryRareBook(models.Model):
    _name = "library.rare.book"
    _description = "Rare Book"
    _inherit = "library.book"

    insured_value = fields.Monetary(currency_field="currency_id")
    currency_id = fields.Many2one("res.currency")

The new model starts with all the fields and methods of library.book, but stores its data in its own table; changing library.book later does not change data of the copy. This pattern is less common than extension. It is most often used with abstract mixins.

4. Mixins: inherit several abstract models

Behaviour that many models need is packaged as an abstract model and mixed in with a list:

Python
class VetPet(models.Model):
    _name = "vet.pet"
    _description = "Pet"
    _inherit = ["mail.thread", "mail.activity.mixin"]

    name = fields.Char(tracking=True)

By inheriting mail.thread the pet gets a chatter, message logging and field tracking; mail.activity.mixin adds scheduled activities. Other widely used mixins are portal.mixin (portal access links) and image.mixin (image sizes). Writing your own mixin is just defining an AbstractModel with the shared fields and methods.

5. Delegation: _inherits

_inherits implements composition: the new model contains a Many2one to a parent record and transparently exposes the parent's fields, so each record is really two rows.

Python
class Employee(models.Model):
    _name = "vet.employee"
    _description = "Vet employee"
    _inherits = {"res.partner": "partner_id"}

    partner_id = fields.Many2one("res.partner", required=True, ondelete="cascade")
    license_number = fields.Char()

Reading employee.name reads the partner's name; creating an employee creates the partner too. Use it when an entity "is a" partner but needs its own table with extra fields, as res.users does with res.partner.

flowchart TB
    subgraph A["_inherit (extension)"]
        P1["res.partner"] --- P2["+ loyalty_level"]
    end
    subgraph B["_inherit + new _name (copy)"]
        BK["library.book"] -->|"copy"| RB["library.rare.book<br/>own table"]
    end
    subgraph C["_inherits (delegation)"]
        EM["vet.employee"] -->|"partner_id"| RP["res.partner"]
    end

Extension keeps one table; a copy creates a new table; delegation joins two tables.

Extending views

Views inherit too, with XML that points to the original view and says where to add elements, using XPath expressions. Chapter 5 covers this in detail.

A runnable stand-in: layering classes with super()

Python's own inheritance is what Odoo builds on. The registry creates the final class from all the contributions in module load order. This stand-in does the same with type() so you can see how super() flows through the chain.

Python Stand-in: modules contribute to one model

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.

Each extension calls super(), so the base behaviour runs once and every module adds its piece. If LoyaltyExtension forgot super(), neither the base confirmation nor the stock step would run, and that is why overriding without super() is dangerous in Odoo.

A second stand-in: delegation with _inherits

Delegation can be mimicked by forwarding attribute access to a parent object, which is essentially what the ORM does with _inherits.

Python Stand-in: _inherits delegation

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. You write class ResPartner(models.Model): _inherit = 'res.partner' and add a field. What happens?

    Classical extension adds to the existing model in place.
  2. 2. What is the risk of overriding action_confirm without calling super()?

    super() continues down the chain. Without it you replace the whole behaviour, including other modules' code.
  3. 3. Which style creates a new table by copying the fields of an existing model?

    A new _name together with _inherit makes a copy with its own table.
  4. 4. How do you give a model a chatter and field tracking?

    mail.thread is an abstract model that adds messaging; fields then use tracking=True.

Summary

  • Extend, never edit: _inherit alone adds fields and methods to an existing model in place.
  • Override methods with the same name and call super() so the chain of modules keeps working.
  • _inherit with a new _name makes a copy in a new table; mixins such as mail.thread are abstract models you add to a list.
  • _inherits delegates to a parent record through a Many2one and exposes its fields.
  • The final class is built from all modules in dependency (load) order.

Next: Odoo Views and the XML Architecture