Use of Different Odoo Decorators
In Odoo, the @api.model, @api.multi, and @api.one decorators are used to define the context in which a method operates on records. These decorators handle how methods interact with single or multiple records and are used in the Odoo ORM. In this article, we’ll explore their differences and provide examples to illustrate when to use each decorator. Understanding these distinctions is essential for writing a maintainable code.
1. @api.model
Purpose
This decorator is used for methods that do not directly operate on specific records but rather at the model level (like creating a record or performing global operations).
Input
The method only has access to the model (self) without reference to specific records.
Use case
When the method doesn’t depend on a particular record. Typically used for methods related to model-wide operations (e.g., create or default_get).
Example
2. @api.multi
Purpose
This decorator allows a method to handle multiple records (self can be a recordset of multiple records).
Behavior
The method operates in bulk and expects to iterate through the records if needed.
Input
self is a recordset that can include one or more records.
Use case
When the method should support both single and multiple records. Typically used for methods like write, unlink, or custom business logic applied to a batch of records.
Example
3. @api.one (Deprecated in Odoo 13 and later)
Purpose
This decorator is used for methods that operate on a single record. It automatically loops through a recordset and applies the method to each record individually.
Behavior
The method receives a single record as self.
Input
self is automatically set to a single record (but the method is still called for each record in the set).
Use case
It simplifies code by removing the need for explicit loops over recordsets. However, it’s less efficient than @api.multi for batch operations because it processes each record separately.
Example
Note: @api.one is deprecated due to inefficiencies and has been removed in Odoo 13+.
Best Practices for Using Odoo Decorators
- Use @api.model for methods that do not depend on specific records.
- Use @api.multi for batch processing on recordsets.
- Avoid @api.one in newer Odoo versions (13+); manually iterate over records if needed.
Wrap-Up
Understanding when and how to use the @api.model, @api.multi, and @api.one decorators is essential for writing a clean code in Odoo. While @api.model is used for methods that don’t depend on specific records, @api.multi is preferred for handling multiple records at once. The @api.one decorator, now deprecated, is no longer recommended for use in newer versions of Odoo.
By applying the best practices outlined in this article, Odoo developers can ensure their code is more aligned with the platform's latest capabilities.
Need more development tips?
Stay tuned to our blog.