Enable Dark Mode!
how-to-create-compute-fields-in-odoo18.jpg
By: Ayana R

How to create compute fields in odoo18

Technical Odoo 18 Odoo Enterprises Odoo Community

Odoo, a versatile and powerful ERP platform, provides developers with tools to create dynamic and automated solutions for business processes. One such tool is the computed field, which allows you to calculate field values dynamically based on other fields in a model.

In this blog, we’ll explore how to create computed fields in Odoo 18 and dive into the critical difference between using the @api.depends decorator and not using it. We’ll also provide practical examples to illustrate the concepts.

What Are Computed Fields?

Computed fields in Odoo are fields whose values are not stored directly in the database but are instead calculated dynamically using a Python function. These fields are ideal for scenarios where a field’s value depends on other fields in the same model or related models, such as calculating a total price based on quantities and unit prices.

Computed fields are defined with the compute parameter, which points to a method responsible for calculating the field’s value. By default, computed fields are read-only, but they can be made editable with additional configurations, such as inverse functions.

Creating a Computed Field in Odoo

To create a computed field, you need to:

  • Define the field in your model with the compute parameter.
  • Write a method to calculate the field’s value.
  • Use the @api.depends decorator to specify dependencies.
  • Set store=True to persist the computed value in the database.

Here’s an example of a computed field that calculates the total price based on the quantity and unit price of items in a model:

from odoo import models, fields, api
class MyCustomModel(models.Model):
    _name = 'my.custom.model'
    _description = 'Custom Model for Compute Field Example'
    name = fields.Char(string="Description")
    unit_price = fields.Float(string="Unit Price")
    quantity = fields.Integer(string="Quantity")
    total_price = fields.Float(string="Total Price",   compute="_compute_total_price", store=True)
    @api.depends('unit_price', 'quantity')
    def _compute_total_price(self):
        for record in self:
            record.total_price = record.unit_price * record.quantity

In this example:

  • The total_price field is a computed field.
  • The store=True parameter ensures that the computed value is saved in the database.
  • The _compute_total_price method calculates the value by multiplying unit_price and quantity.
  • The @api.depends decorator ensures the field is automatically updated when either unit_price or quantity changes.

The Role of @api.depends

The @api.depends decorator is used to specify which fields the computed field depends on. When any of these dependent fields change, Odoo automatically triggers the computation of the computed field and updates its value (and stores it if store=True). This ensures that the computed field always reflects the latest values of its dependencies.

Using @api.depends

In the example above:

  • The @api.depends('unit_price', 'quantity') decorator tells Odoo to recompute total_price whenever either of those two fields changes.
  • If store=True, the recomputed value is saved to the database, reducing the need for recalculation when the field is accessed later.
  • This ensures that the total_price field is always up-to-date without requiring manual intervention.

What Happens Without @api.depends?

If you omit the @api.depends decorator, Odoo will not know which fields trigger the computation of the computed field. As a result, the computed field will only be calculated in specific scenarios, such as:

  • When the record is created or updated manually.
  • When the field is explicitly accessed (e.g., displayed in a form view or used in a report).

This can lead to outdated or incorrect values in the computed field, especially in dynamic scenarios where dependent fields change frequently. Additionally, if store=True, the stored value may not be updated correctly, leading to inconsistencies.

Example Without @api.depends

from odoo import models, fields, api
class MyCustomModel(models.Model):
    _name = 'my.custom.model'
    _description = 'Custom Model for Compute Field Example'
    name = fields.Char(string="Description")
    unit_price = fields.Float(string="Unit Price")
    quantity = fields.Integer(string="Quantity")
    total_price = fields.Float(string="Total Price", compute="_compute_total_price", store=True)
    def _compute_total_price(self):
        for record in self:
            record.total_price = record.unit_price * record.quantity

In this case:

  • The total_price field will not automatically update when unit_price or quantity changes.
  • The computation will only occur when the field is accessed or when the record is saved.
  • Even with store=True, the stored value may become outdated if dependent fields change without triggering a recomputation, leading to inconsistent data.

The Role of store=True

Setting store=True on a computed field instructs Odoo to persist the computed value in the database. By default, computed fields are not stored (store=False), and their values are calculated on the fly each time they are accessed.

When to Use store=True

  • Use store=True when the computed field is accessed frequently, and the computation is resource-intensive.
  • Use it when you need to search or filter records based on the computed field.
  • Avoid store=True for simple calculations or fields that are rarely accessed, as the storage overhead may outweigh the benefits.

By following the guidelines and examples in this blog, you can effectively create computed fields in Odoo 18, leverage @api.depends for automatic updates, and use store=True to optimize performance. Whether you’re building a simple calculation or a complex business rule, understanding the interplay between @api.depends and store=True is essential for building robust, efficient, and user-friendly Odoo applications.

To read more about How to Add Inverse Function for Compute Fields in Odoo 18, refer to our blog How to Add Inverse Function for Compute Fields in Odoo 18.


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



0
Comments



Leave a comment



whatsapp_icon
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