Passa al contenuto
Menu
È necessario essere registrati per interagire con la community.
La domanda è stata contrassegnata
2 Risposte
2832 Visualizzazioni

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
Abbandona
Autore Risposta migliore

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
Abbandona
Risposta migliore

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
Abbandona
Post correlati Risposte Visualizzazioni Attività
3
feb 23
5564
4
apr 24
3043
1
feb 24
1917
3
lug 23
3336
2
mag 23
3436