Enable Dark Mode!
how-to-add-a-computed-field-in-odoo-19.jpg
By: Ramsina K

How to Add a Computed Field in Odoo 19

Technical Odoo 19 Employees

Odoo 19 continues to evolve as a powerful, all-in-one business management platform, offering enhanced capabilities for developers to create dynamic and intelligent applications. One of the most valuable features for customizing Odoo is computed fields, which allow you to automatically calculate values based on other fields in your model.

In this comprehensive guide, we'll explore how to effectively implement computed fields in Odoo 19, highlighting the latest best practices and demonstrating practical examples to help you leverage this powerful feature in your custom modules.

Understanding Computed Fields in Odoo 19

Computed fields are special fields whose values are not stored directly in the database (unless specified) but are calculated on the fly using a Python method. These fields are incredibly useful for:

  • Calculating values based on other fields (e.g., total price from quantity and unit price
  • Formatting or combining field values
  • Implementing business logic that depends on multiple factors
  • Creating derived data without manual input

Creating a Basic Computed Field

Let's start with a practical example. Suppose we have a sales order model where we want to calculate the total price based on quantity and unit price.

from odoo import models, fields, api
class CustomSalesOrder(models.Model):
    _name = 'custom.sales.order'
    _description = 'Custom Sales Order'
    
    name = fields.Char(string="Order Reference", required=True)
    unit_price = fields.Float(string="Unit Price", digits='Product Price')
    quantity = fields.Integer(string="Quantity", default=1)
    total_price = fields.Float(
        string="Total Price", 
        compute="_compute_total_price",
        digits='Product Price',
        store=True  # This stores the value in database
    )
    
    @api.depends('unit_price', 'quantity')
    def _compute_total_price(self):
        for record in self:
            record.total_price = record.unit_price * record.quantity

Key Components Explained

  • Field Definition: The total_price field is defined with the compute parameter pointing to the method that will calculate its value.
  • @api.depends Decorator: This crucial decorator specifies which fields the computation depends on. When any of these fields change, Odoo automatically recalculates the computed field.
  • store=True Parameter: This determines whether the computed value is stored in the database. Storing values improves performance but increases database size.

Advanced Computed Field Techniques

Computed Fields with Related Models

Computed fields can also depend on fields from related models using dot notation:

python
class SaleOrderLine(models.Model):
    _name = 'custom.sale.order.line'
    _description = 'Custom Sale Order Line'
    
    order_id = fields.Many2one('custom.sales.order', string="Order")
    product_id = fields.Many2one('product.product', string="Product")
    quantity = fields.Integer(string="Quantity", default=1)
    
    # This field depends on a field from a related model
    currency_id = fields.Many2one(
        related='order_id.currency_id',
        string="Currency",
        store=True
    )

Conditional Computations

You can implement complex business logic in your computed fields:

@api.depends('quantity', 'unit_price', 'discount_percent')
def _compute_total_price(self):
    for record in self:
        base_price = record.unit_price * record.quantity
        discount = base_price * (record.discount_percent / 100)
        record.total_price = base_price - discount

Multi-field Dependencies

Computed fields can depend on multiple fields, including those from related models:

@api.depends('order_line_ids.price_subtotal', 'global_discount')
def _compute_total_amount(self):
    for order in self:
        subtotal = sum(line.price_subtotal for line in order.order_line_ids)
        order.total_amount = subtotal - (subtotal * order.global_discount / 100)

The Role of @api.depends

The @api.depends decorator is essential for proper computed field behavior in Odoo 19. It serves two crucial purposes:

  • Automatic Recalculation: It tells Odoo which field changes should trigger a recomputation of the computed field.
  • Optimized Performance: It helps Odoo's ORM optimize when and how computations occur, preventing unnecessary calculations.

Without proper dependency declaration, your computed fields may display outdated values or cause performance issues.

Store=True vs. Store=False

Understanding when to store computed values is crucial for application performance:

  • store=True:
    • Values are persisted in the database
    • Better performance for frequently accessed fields
    • Allows searching, sorting, and grouping by the field
    • Increases database storage requirements
  • store=False (default):
    • Values are calculated on-the-fly when accessed
    • Reduces database storage
    • Better for rarely accessed or complex calculations
    • Cannot be used for searching, sorting, or grouping

Best Practices for Computed Fields in Odoo 19

  1. Always use @api.depends: Never omit this decorator as it ensures data consistency.
  2. Optimize database usage: Use store=True judiciously based on how frequently the field is accessed.
  3. Handle empty records: Always account for cases where dependent fields might be empty.
  4. Consider performance: For computations involving large datasets, optimize your code to minimize database queries.
  5. Test thoroughly: Computed fields can have unexpected behaviors in edge cases.
  6. Use appropriate field types: Ensure your computed field uses the correct field type for the calculated value.

Computed fields are a powerful feature in Odoo 19 that allow you to create dynamic, intelligent applications that automatically respond to data changes. By understanding how to properly implement computed fields with the @api.depends decorator, when to use store=True, and how to avoid common pitfalls, you can significantly enhance your Odoo modules' functionality and user experience.

Remember that while computed fields offer great flexibility, they should be used judiciously to maintain application performance. Always test your implementations thoroughly and consider the database impact of storing computed values.

To read more about How to Create Computed Fields in Odoo 18, refer to our blog How to Create Computed 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