Skip to Content
Menu
This question has been flagged
2 Replies
1523 Views

Hello to all.

I have just started reading the Odoo developer tutorial.

I'm starting to be quite advanced, and thinking about it I'm having a little trouble rereading the code I wrote for the iterations on self.

Example:

class
EstateProperty(models.Model):
    _name = "estate.property
    _description = "Estate property"
...
offers_ids = fields.One2many("estate.property.offer", "property_id",string="Offers")
@api.depends("offers_ids.price")
    def _compute_best_price(self):
        for property_ in self:
            offers_price = property_.mapped('offers_ids.price')
            property_.best_price = max(offers_price) if len(offers_price) != 0 else 0




In this code, why do a loop on self.

From my understanding of the code I wrote when reading the tutorial, the modification of the price of a property offer leads to a calculation to determine the best offer (the most expensive)

Why changing the price of ONE offer leads to a loop on ALL the existing offers to recalculate their "best_price"? 

I noticed that the following code (which seems more logical to read) also works

self.best_price = max(...)

I also noticed that displaying a calculated field in a "TREE" view crashes the application if you don't do a "for item on self".

So is the following logic OK ? : 
- Do a loop on self on calculated fields to be displayed in a tree view
- No loop on self, in calculated fields to be displayed in a form view

Thanks in advance for your answers.

Avatar
Discard
Author Best Answer

Hello,

Thank you for your answer.

So contrary to what I said, making a loop

for property in self :

in an action called in a form view does not loop over all properties, but only over one (the one of the form)

It didn't seem clear to me when I reread the code, but it's ok now


Thanks again.

Avatar
Discard
Best Answer

Hi,

if your compute field is present in the tree/list view, the compute function will be called and it will compute for all the records in the list view.If you didn't iterate your 'self' you will get an error message because multiple records id will be got because it is a list/tree view. But for the form view, there will be only one record. So you don't need to iterate through 'self'.

But I would recommend always iterating self to avoid any traceback in the future.

Regards

Avatar
Discard
Related Posts Replies Views Activity
3
Feb 23
3649
4
Apr 24
863
1
Feb 24
604
3
Jul 23
1345
2
May 23
1609