Decorators are a powerful feature in Odoo that help you modify the behavior of methods and models. In Odoo 19, decorators play a crucial role in defining model behavior, API constraints, and method execution. Let's explore the most commonly used decorators.
1. @api.model
The @api.model decorator is used for methods that don't operate on a specific recordset. These methods work at the model level rather on individual records.
@api.model
def create(self, vals):
# Create a new record
return super().create(vals)
2. @api.depends
This decorator defines field dependencies for computed fields. When any of the dependent fields change, the computed field is automatically recalculated.
@api.depends('price', 'quantity')
def _compute_total(self):
for record in self:
record.total = record.price * record.quantity
3. @api.onchange
The @api.onchange decorator triggers a method when specific fields are modified in the user interface, allowing you to update other fields dynamically.
@api.onchange('partner_id')
def _onchange_partner(self):
if self.partner_id:
self.delivery_address = self.partner_id.address
4. @api.constrains
This decorator validates field values and raises an error if constraints are violated. It's triggered when the specified fields are modified.
@api.constrains('age')
def _check_age(self):
for record in self:
if record.age < 18:
raise ValidationError("Age must be at least 18")
5. @api.model_create_multi
Introduced for batch creation optimization, this decorator handles creating multiple records efficiently in a single call.
@api.model_create_multi
def create(self, vals_list):
# Efficiently create multiple records
return super().create(vals_list)
6. @api.autovacuum
This decorator marks a method to be called by Odoo's autovacuum cron job for automatic cleanup tasks.
@api.autovacuum
def _gc_old_sessions(self):
# Clean up old session data
deadline = fields.Datetime.now() - timedelta(days=30)
self.search([('date', '<', deadline)]).unlink()
Conclusion
Understanding and properly using decorators in Odoo 19 is essential for building robust and efficient modules. They help you write cleaner code while leveraging Odoo's built-in functionality for field computation, validation, and event handling. Master these decorators to unlock the full potential of Odoo development.
