Complete Guide for Using Method Decorators in Odoo18

HISHAM
December 28, 2024
method-decorators-in-odoo18

Method decorators in Odoo18 are essential to modify or extend existing methods without changing any core implementation. Anyone can easily add new functionality using Odoo18’s decorators to wrap methods and its makes your business operations smoother and simplifies your work with the Odoo framework. Learning when and how to use decorators can greatly improve your development process, especially when building complex enterprise resource Planning (ERP) applications.

In this blog, we are going to discover how method decorators in Odoo18 can enhance your development process. We’ll explore its significance, how method decorators simplify tasks, and which key decorators you should know to simply your UAE business in 2025

Discover Essential Odoo18 Method Decorators and its Common Uses

@api.model

@api.model methods are independent of any specific record. They can applied in the context of a model rather than individual records, and do not require the existence of a particular record set.

Example

from odoo import models, api

class ExampleModel(models. Model):

_name = 'example.model'

@apt.model

def example_method(self): # No particular records needed return "Records are not needed to call this method"

For the case mentioned in above example ,the example_method is accessible from model level and can handle logic without depending on specific record context.

@api.depends

For computed fields, @api.depends is a must. The fields that the calculated method depends on are specified in this decorator, ensuring that any changes to these dependent fields trigger a recalculation of the method.

Example

lass ExampleModel (models.Model):

_name = 'example.model'

custom_field = fields. Integer (compute='_compute_custom_field')

@api.depends('custom_field_2')

def_compute_custom_field(self):

for record in self:

record.custom_field = record.custom_field_2 + 4

if the custom_field_2 is changed _compute_custom_field will recalculated as like this

@api.constrains

For example, whenever the custom_field_2 changes, the _compute_custom_field method will recalculate.

Example

from odoo import models, fields, api from odoo.exceptions import ValidationError

class ExampleModel (models.Model):

_name = 'example.model'

weight = fields.Float(string="Weight")

@api.constrains ('weight')

def _check_weight(self):

for record in self:

if record.weight < 0:

raise ValidationError("Weight cannot be negative.""


The _check_weight function ensures that the weight field cannot contain negative values; if it does, an exception is triggered.

@api.onchange

This decorator used for methods that need to called every time a specific UI field changes and stores data in form views and is often used to dynamically update fields based on user input.

Example

class ExampleModel(models.Model):

_name = 'example.model'

custom_amount = fields.Float()

custom_discount = fields.Float()

@api.onchange('custom_discount')

def onchange_custom_discount(self):

if self.custom_discount:

self.custom_amount = self.custom_amount (self.custom_amount *

(self.custom_discount / 100))

In this method, whenever the ‘custom_discount’ field is changed, the function _onchange_custom_discount is called, updating the custom_amount accordingly.

@api.returns

The @api.returns decorator used to return instances of a particular model. It requires three parameters: downgrade, which changes the record-based output to traditional format; upgrade, which converts the traditional output into record-based format; and model, which represents the model’s name or “self” for the current model. By using this decorator, the method can return an ID, a list of IDs, or a record set, with the output format adjusted based on the process.

class ExampleModel(models.Model):

_name = 'example.model'

@api.returns('self')

def copy(self, default=None):

# Write your custom logic for copying a record.

return super(ExampleModel, self).copy default)

In the above example, the method copy ensures that after finishing its work, it returns a new instance of the current model’s recordset.

@api.model_create_multi

This decorator is mainly use to creating multiple records at a time. It reduces the number of database transactions required which optimizes the performance.

Example

class ExampleModel (models.Model):

_name = 'example.model'

@api.model_create_multi

def create(self, vals_list):

# Optimized creation of multiple records

return super (ExampleModel, self).create(vals_list)

The method can create multiple records efficiently by processing them in batches using @api.model_create_multi.

@api.autovacuum

You can mark a method to run as part of the daily vacuum cron job using the autovacuum method decorator, model ir.autovacuum. This includes tasks like garbage collection, which help with resource management without requiring a separate cron job. With this decorator, you don’t have to create a separate cron job for each task, and you can use it to ensure that essential maintenance out automatically at regular intervals.

@api.depends_context

The @api.depends_context decorator indicates that the non-stored “compute” method relies on specific contextual values. context keys. In the context dictionary, each argument represents a key.

Example

from odoo import models, fields, api

class ExampleModel(models.Model):

_name = 'example.model'

amount_price = fields. Float(compute='_compute_amount_price')

@api.depends_context('amount_rate')

def _compute_amount_price(self):

for rec in self:

amount_rate = self.env.context.get('amount rate', 0.0)

rec.amount_price = rec.list_price* (1 - amount_rate / 100)

In this example, if amount_rate is available in the context, then amount_price is set as shown. If amount_rate is not available, it will be zero.

Odoo 18’s method decorators are pretty powerful tools that enhance the capability of the framework. They make the developer’s life easier by giving programmers the opportunity to develop clear, effective, and reusable code.Knowing how to use these decorators will improve your Odoo apps, making them more reliable and intuitive.

Through using the method decorators in Odoo18, you are capable of fully unleashing the potency of features offered by Odoo to create new models or better improve existing models. As such, it will enhance better solutions towards your firm’s needs.

Odoo 18’s method decorators are powerful implements that can significantly enhance the functionality of your ERP Software Odoo developers can easily modify or extend existing methods, automate processes, enforce data integrity also streamline complex workflows without customizing the core code

As we’ve seen throughout this blog, knowing how to apply decorators – @api.model, @api.depends, @api.onchange, and many others,  

By mastering these decorators, you’ll be qualified to handle even the most complex tasks in Odoo with ease, ensuring your business operations run smoothly and efficiently.

As we move towards 2025, using these decorators will give you a competitive advantage, helping you to develop powerful, scalable Odoo ERP Software to fulfill the needs of your UAE-based business and beyond. Want help? Reach out today for a personalized consultation, and let’s collaborate with us to develop effective Custom ERP solutions to push your business forward

"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 *