Skip to Content
Menu
This question has been flagged
3 Replies
17966 Views

I have to set a field that compute the difference between the old and the new value of a float field, I defined an auxiliary field that contain the old value, but the problem that the value of auxiliary field replaced by the new value then the diff always Zero.

   @api.multi
def _computeVar(self): for record in self: 
            record .val_aux= record .val
            record .val_diff= record .val-record.val_aux

    val=fields.Float(string='val')
val_aux=fields.Float(string='val aux',compute='_computediff', readonly=True) val_diff= fields.Float(string='val diff',compute='_computediff', readonly=True)


 And when wereplace the order of line of the fuction we will have a problem : field used before calculated.
How to solve this problem
Avatar
Discard

you cant calculate them because your fields are readonly as i think

Best Answer

You just need to reorder your calculation of the fields to not override the old values. This should work:


    @api.multi
def _computeVar(self):
for record in self:
record.val_diff= record.val - record.val_aux
            record.val_aux= record.val
val=fields.Float(string='val')
val_aux=fields.Float(string='val aux',compute='_computediff', readonly=True)
val_diff= fields.Float(string='val diff',compute='_computediff', readonly=True)


Avatar
Discard
Best Answer

The above code normally must give zero value in the difference field 'val_diff'

to achieve your request

I have to set a field that compute the difference between the old and the new value of a float field

I suggest the following solution instead of the one defined above,

@api.one
@api.depends('val','old_val') 
def _computediff(self):
    self.val_diff= self.val-self.old_val

val=fields.Float(string='val') 
old_val=fields.Float(string='Old Value') 
val_diff= fields.Float(string='val diff',compute='_computediff', readonly=True)

the old_val field should be updated in the write method as follows

def write(self,cr,uid,ids,vals,context=None):
    ....
    """before calling the super(<your_class_name>,self).write(cr,uid,ids,vals,context),
        gt the old_val field from the persistent database """
    o = self.pool.get('your_class_name').browse(cr,uid,ids[0])
    vals['old_val'] = o.val
    ...
    res = super(<your_class_name>,self).write(cr,uid,ids,vals,context)
    return res

you have to set the initial value of the field 'old_val' to be 0.0, this will be updated in the create method so you are sure that the _computediff will work correctly


I replaced the @api.multi with @api.one based on this link, check Computed fields and default values

 Note :I used in the openERP 7 notation for the write method

Avatar
Discard
Related Posts Replies Views Activity
0
Dec 15
5706
5
Nov 15
4745
1
Jul 15
6609
0
Oct 17
8312
1
Feb 16
2856