Enable Dark Mode!
method-decorators-in-odoo-14.jpg
By: Sonu S

Method Decorators in Odoo 14

Technical Odoo 14

Decorators can be used to update the method environment. It is helpful for extending the characteristics of a function or adding functionality to a process that has specific requirements. These decorators explicitly pass parameters to the method. This allows you to write functions smoothly and avoid complexity. There are many types of decorators used in odoo that are described as follows:
This blog is about the method of decorators in odoo 14.
api.depends
Depends decorator is used to extend the behavior of a field function when this calculation depends on other fields. As shown in the example, the balance field is a computed field that depends further on two fields: debit and credit. Thus we can depend on many fields to compute a field. Here is an example of the code:
@api.depends('debit', 'credit')
def _compute_bank_balance(self):
for record in self:
record.balance = record.debit - record.credit
api.model
This decorator is used on methods where the contents are not relevant. Here the self is a record set, and the model is more significant than its contents. Here is an example of the code:
@api.model
    def name_create(self, name):
        name, email = self.get_name_email(name)
        contact = self.create({'name': name, 'email': email})
        return contact.name_get()[0]
api.onchange
This decorator is used when there is a need to change a field’s value according to one field. It may be useful to update other fields based on this field value automatically. Here is an example code:
@api.onchange('state')
    def _onchange_state(self):
        if self.state == 'done':
            self.partner_id.survey_state = self.state
api.constraints
The decorator states which fields are included in the constraint, such that the constraint is automatically validated when one of them is updated. This method is expected to raise an exception if its condition is not satisfied. Here is an example of the code:
 @api.constrains('to_date', 'from_date')
    def date_check(self):
        """ Date validation"""
        for rec in self.filtered(lambda l: l.to_date < l.from_date):
            raise ValidationError('Sorry Invalid Date!!')
api.model_create_multi
It takes a list of dictionaries and creates multiple records. The method can be single or multiple lists. Here is an example of the code:
@api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            score_vals = self._get_answer_score_values(vals)
            if not vals.get('answer_score'):
                vals.update(score_vals)
        return super(SurveyUserInputLine, self).create(vals_list)
api.depends_context
This method decorator gets the context dependencies of unsaved compute methods. Each argument contained in this method is the key to the context dictionary.  Here is an example code:
@api.depends('employee_ids')
@api.depends_context('company')
    def _compute_company_employee(self):
        for rec in self:
            rec.employee_id = self.env['hr.employee'].search([('id', 'in', rec.employee_ids.ids),     ('company_id', '=', self.env.company.id)], limit=1)
api.autovacuum
It is a method used for garbage collection, like methods that do not deserve a specific cron job. Here is an example of the code:
@api.autovacuum
    def _gc_messages(self):
           timeout_ago = datetime.datetime.utcnow()-datetime.timedelta(seconds=TIMEOUT*2)
        domain = [('create_date', '<',    timeout_ago.strftime(DEFAULT_SERVER_DATETIME_FORMAT))]
           return self.sudo().search(domain).unlink()
Decorators are an elegant way to extend the functionality of the original function without changing the source code. In addition, the decorator you define can accept arguments or fall back to predefined default arguments.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message