DEV Community

Jeevachaithanyan Sivanandan
Jeevachaithanyan Sivanandan

Posted on

Odoo : Computed Fields

In Odoo development, the decision to use a computed method for a field or not depends on the nature of the data and the behavior you want to achieve in your Odoo model. Here are some guidelines:

Use a Computed Method When:

Dynamic Computation: If the value of the field depends on dynamic or complex calculations involving other fields or external data, use a computed method. This allows you to write custom logic to compute the field value.

  • @api.depends('field1', 'field2')
    def _compute_custom_field(self):
    for record in self:
    record.custom_field = record.field1 + record.field2

  • Dependency on Related Models: When the field value depends on fields in related models, a computed method is suitable. This is often the case when using Many2one or One2many fields.

  • @api.depends('partner_id.user_id')
    def _compute_user_id(self):
    for record in self:
    record.user_id = record.partner_id.user_id

  • Conditional Computation: If the field value needs to be computed conditionally based on certain criteria, a computed method provides the flexibility to handle such conditions.

@api.depends('status')
def _compute_custom_status(self):
for record in self:
if record.status == 'approved':
record.custom_status = 'Active'
else:
record.custom_status = 'Inactive'

Avoid Computed Method When:

Simple Data Retrieval: If the field value can be retrieved directly from another field without complex computation, consider using the related attribute instead of a computed method.

  • user_id = fields.Many2one('res.users', string='User', related='partner_id.user_id', readonly=True)

  • Performance Concerns: Computed methods can have performance implications, especially if the computation involves heavy processing or if the field is used in large datasets. In such cases, consider using a stored computed field or optimizing the computation.

  • Read-Only Fields: If the field is read-only and its value does not need to change dynamically, you might not need a computed method. A static value or a value fetched from a related field could be sufficient.

default_value = fields.Char(string='Default Value', default='Static Value', readonly=True)

In summary, use computed methods when you need dynamic or complex computation, and use simpler methods like related or default values when the field value can be determined without the need for custom logic. Always consider the nature of the data and the requirements of your specific use case.

Top comments (0)