In Odoo, when defining fields in a model, you often need to establish relationships between fields in the same model or related models. Two common attributes used for this purpose are related and compute. Let's explore when and how to use these attributes, and when not to use them based on your requirements.
related Attribute:
When to Use:
-
Direct Field Mapping:
- Use
relatedwhen the value of a field in your model can be directly fetched from another field, either within the same model or in a related model.
- Use
sales_person_id = fields.Many2one(related='res.users', string='Salesperson', store=True)-
No Custom Computation:
- Use
relatedwhen there's no need for custom computation or logic to determine the value of the field. It provides a straightforward way to link fields.
- Use
Example:
`class ProjectTask(models.Model):
_name = 'project.task'
# Use related when sales_person_id can be directly fetched from res.users
sales_person_id = fields.Many2one(related='res.users', string='Salesperson', store=True)`
compute Attribute:
When to Use:
-
Custom Computation:
- Use
computewhen the value of a field needs to be dynamically computed based on custom logic, other fields, or conditions.
- Use
sales_person_id = fields.Many2one('res.users', string='Salesperson', compute='_compute_sales_person_id', store=True)-
Dependency on Other Fields:
- Use
computewhen the value depends on other fields, and you want the field to be automatically recomputed when the dependent fields change.
- Use
Example:
`class ProjectTask(models.Model):
_name = 'project.task'
# Use compute when custom logic is needed to determine sales_person_id
@api.depends('some_dependency_field')
def _compute_sales_person_id(self):
for task in self:
task.sales_person_id = some_function_to_determine_sales_person_id(task.some_dependency_field)
sales_person_id = fields.Many2one('res.users', string='Salesperson', compute='_compute_sales_person_id', store=True)`
When Not to Use:
- Avoid Redundancy:
- Avoid using both
relatedandcomputein the same field definition unless necessary. If you userelated, it assumes direct field mapping, and adding acomputemethod might lead to redundant computations.
- Avoid using both
# Avoid this unless necessary
sales_person_id = fields.Many2one(related='res.users', string='Salesperson', compute='_compute_sales_person_id', store=True)
Conclusion:
Choosing between related and compute depends on the nature of the data and the logic involved. Use related for direct field mapping without custom computation and compute when dynamic calculations or custom logic are needed.
By understanding the distinctions between these attributes, you can make informed decisions when designing your Odoo models.
Top comments (0)