The ORM system of Odoo has become more advanced with Odoo 18 while maintaining its powerful capabilities. Developers who create custom modules for Odoo need to understand @api decorators because they create efficient and future-proof code that is also clean. The decorators function as essential building blocks to create dynamic models which operate according to your exact requirements.
This article demonstrates effective and useful methods to implement core @api decorators including @api.depends, @api.onchange, @api.model and @api.constrains.
The Odoo framework depends on each of these decorators for its operation. The correct implementation of these decorators enables automated processes and user-triggered changes and data validation and additional functionality. The article demonstrates practical applications of these decorators through real-world examples which enhance system performance and simplify logic while making maintenance easier.
The effective use of these decorators will provide Odoo 18 developers with a substantial advantage when they create custom applications or enhance existing ones.
1. @api.depends – Computed Fields That Stay in Sync
Use Case: Auto-calculate order total when line items change.
from odoo import models, fields, api
class SaleOrder(models.Model):
_inherit = 'sale.order'
total_qty = fields.Float(compute='_compute_total_qty', store=True)
@api.depends('order_line.product_uom_qty')
def _compute_total_qty(self):
for order in self:
order.total_qty = sum(order.order_line.mapped('product_uom_qty'))
Tip: Always use store=True for performance if it’s queried often.
2. @api.onchange – Real-Time Field Logic in Forms
Use Case: Auto-fill product price when product is selected.
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
@api.onchange('product_id')
def _onchange_product_id_set_price(self):
if self.product_id:
self.price_unit = self.product_id.lst_price
Pro Tip: Use onchange for UI-only logic. It won’t be triggered in create() or write().
3. @api.model – Model-level Operations & Custom Create Hooks
Use Case: Auto-generate a name using a sequence.
class CreditLimit(models.Model):
_name = 'credit.limit'
name = fields.Char(string="Name", required=True, copy=False, readonly=True, default='New')
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if not vals.get('name') or vals['name'] == 'New':
vals['name'] = self.env['ir.sequence'].next_by_code('credit.limit.seq') or 'CL000'
return super().create(vals_list)
Note: @api.model_create_multi is a newer, optimized version for bulk create.
4. @api.constrains – Validation Logic That Saves Your Data
Use Case: Prevent saving if quantity is negative.
from odoo.exceptions import ValidationError
class CreditLimit(models.Model):
_name = 'credit.limit'
quantity = fields.Float(string="Quantity")
@api.constrains('quantity')
def _check_quantity_positive(self):
for record in self:
if record.quantity < 0:
raise ValidationError("Quantity must be positive.")
Tip: Triggers only on record save (not on form change).
5. @api.ondelete – Custom Cleanup Logic
Use Case: Prevent deletion if the record is confirmed.
from odoo import models, _
from odoo.exceptions import UserError
from odoo.api import ondelete
class AccountAccount(models.Model):
_inherit = 'account.account'
@ondelete(at_uninstall=False)
def _unlink_except_contains_journal_items(self):
for account in self:
journal_item_exists = self.env['account.move.line'].search_count(
[('account_id', '=', account.id)], limit=1
)
if journal_item_exists:
raise UserError(_('You cannot delete the account "%s" because it contains journal items.') % account.display_name)
6. @api.depends_context – React to Context Changes
@api.depends_context(‘lang’)
def _compute_description(self):
for record in self:
record.description = self.with_context(lang=self.env.context.get('lang'))._get_translation()
Useful for context-sensitive fields (e.g., multi-language descriptions).
Bonus Tips
Avoid mixing @api.onchange and @api.depends on the same method.
Use @api.model_create_multi for performance when overriding create().
Avoid triggering expensive logic inside @api.depends (like DB search calls).
Always consider @api.depends_context when context values are vital.
Final Thoughts: Why Mastering @api Decorators in Odoo 18 Matters
The mastery of @api decorators in Odoo 18 serves as a technical ability and strategic benefit for Odoo developers who want to create high-quality scalable applications. The correct application of @api.depends, @api.onchange, @api.model and @api.constrains decorators together with full understanding enables numerous benefits which elevate your coding practice to the next level.
Your first achievement will be writing code that is both clean and logical. The @api decorator enables automatic execution of proper actions at suitable times thus preventing your models from becoming cluttered with manual checks and updates. The resulting codebases become more intuitive and easier to read while maintaining better organization.



