Method Decorators in Odoo 17

HARSHAD
June 24, 2024
decorators in odoo 17

Decorators in Odoo 17 change how methods in models, controllers, and other components behave. The function to which the decorator is attached can have new functionalities added to it, or its current functionalities modified.

In Odoo 17, the following decorators are frequently used:

@api.model

The “@api.model” decorator is utilized in Odoo for methods in which the “self” represents a set of records; nevertheless, the model itself is the only thing that matters, not the records it contains. This decorator comes in handy when transferring code from an older to a newer version of Odoo.

def get_total_books(self):

"""
Method to get the total number of books in the library. This method only deals with the Library model itself. """
library_count = self.env['library'].search_count([])
return library_count

@api.autovacuum

Odoo’s “@api.autovacuum” decorator plans tasks to execute in tandem with the cron job that does the daily vacuum (it. autovacuum). It’s perfect for carrying out duties akin to garbage collection that need to be cleaned up every day without requiring a special cron job entry. By automating normal cleanup tasks, this decorator assures database optimization and makes maintenance easier.

def remove_inactive_users(self): """Remove inactive user records."""

self.env['res.users'].search([('active', '=', False)]).unlink()

@api.constrains

In Odoo, a method’s constraint dependencies are set by the ‘@api.constrains’ decorator. It only triggers the method when specific fields are included in the creating or writing call and if they are present in the view. Dotted names are ignored and only plain field names are supported. If the check fails, this decorator is usually used to raise a ValidationError.

@api.constrains('amount_total') def _check_amount_total(self):

for order in self:
if order.amount_total <= 0:
raise ValidationError("The total amount of the order must be greater than zero.")

@api.depends

The field dependencies for computed fields in Odoo are specified using the ‘@api.depends’ decorator. It tells Odoo that the value of the computed field depends on the values of other fields so that when any of its dependencies change, the computed field’s value is updated.

@api.depends('cost_price', 'sale_price') def _compute_profit_margin(self):

for product in self:
if product.cost_price and product.sale_price:
product.profit_margin = ((product.sale_price - product.cost_price) / product.cost_price) * 100
else:
product.profit_margin = 0.0
Every time the fields "cost price" and "sale price" change, this method is recalculated.

@api.model_create_multi

One dictionary or a collection of dictionaries can be used to produce numerous records using the Odoo @api.multi decorator. It helps to increase productivity and efficiency while creating records in mass. The values are passed to the method as arguments.

def create(self, vals):

cashboxes = super(AccountBankStmtCashWizard, self).create(vals) cashboxes._validate_cashbox()
return cashboxes

@api.onchange

When specific fields within form views change, Odoo’s “@api.onchange” decorator immediately initiates methods. When a model’s defined fields are modified, the methods marked with this decorator are called, allowing for dynamic updates and user-input-driven activities.

@api.onchange('partner_id')

def _onchange_partner_id(self):
if self.partner_id:
self.payment_term_id = self.partner_id.payment_term_id

@api.ondelete

In Odoo, a method designated to be called when records are being unlinked (deleted) is indicated by the decorator ‘@api.ondelete’. It is frequently used to stop records from being erased during module uninstallation—such as lines on submitted entries—because altering the unlink() function would not accomplish this.

Setting parameters:

* at_uninstall: A boolean parameter that controls whether or not the decorated method is invoked when a module is being uninstalled. If False, the method’s faults won’t stop the module from uninstalling.

@api.ondelete(at_uninstall=False) def _unlink_if_not_done(self):

if any(batch.state == 'done' for batch in self):
raise UserError(_("You cannot delete Done batch transfers."))

@api.returns

To define the return type of methods that return instances of a specific model, use the decorator ‘@api.returns’. It modifies the method output to conform to the record style (returning record) or traditional style (returning IDs or False) of the Odoo API.

Setting parameters

  • model: Indicates the name of the current model, sometimes known as “self.”
  • downgrade: An optional feature that allows the output to be produced in traditional style instead of record style.
  • Upgrade: An optional feature that allows you to switch from traditional to record-style output.
@api.mode @api.returns('res.partner') def find_partner(self, arg):

# Return some record

return self.env['res.partner'].search([('name', '=', arg)]) # Traditional style call

partner_id = model.find_partner(arg) # Record style call

partner_record = recs.find_partner(arg)

"Unlock the Full Potential of Your Business with Odoo ERP!"

"Get a Cost Estimate for Your ERP Project, Absolutely FREE!"

Get a Free Quote

Leave a Reply

Your email address will not be published. Required fields are marked *