1
votes

I have some data in a tree structure. One of the fields are computed (not stored) using data from the children. In a form view, I show the computed field and the parent field.

Because of this, I end up reading many records from the model - and Odoo seems to compute the computed field for all of these records, even though the view only needs the computed field for one record.

I thought this was caused by the prefetch mechanism, but I tried to set prefetch_fields=False in the context, and that didn't help.

Any idea how I can avoid computing all the unnecessary values? (Storing the computed field is not an option).

A quick example to give an idea of the construction:

parent_id = fields.Many2one(...)
child_ids = fields.One2many(...) # Inverse parent relation
comp = fields.Integer(compute="_compute_comp")

@api.one
def _compute_comp(self):
    sum = 0
    for c in self.child_ids:
        sum += c._get_complicated_value()
    self.comp = sum

and a view with:

<field name="parent_id" />
<field name="comp" />

comp is always computed for the children's children. With <field name="parent_id" /> it is also computed for ALL the parent's children.

1

1 Answers

1
votes

you can use @api.depends

@api.depends

This decorator will trigger the call to the decorated function if any of the fields specified in the decorator is altered by ORM or changed in the form:

@api.depends('name', 'an_other_field')
def afun(self):
   pass

Note:

when you redefine depends you have to redefine all @api.depends, so it loses some of his interest.

One of the great improvement of the new API is that the depends are automatically inserted into the form for you in a simple way. You do not have to worry about modifying views anymore.

@api.one
@api.depends('child_ids')
def _compute_comp(self):
    sum = 0
    for c in self.child_ids:
       sum += c._get_complicated_value()
    self.comp = sum