This question has been flagged
2 Replies
6212 Views

Hi, I am on odoo 11.

I have difficulties to reuse the values of my model when I overwrite the write method.

I have a class Truck. 

class Truck(models.Model):    
    _name = "hr.ext.truck"
    _description = "Truck"
    
    name = fields.Char()         
    kilometers = fields.Char()
    previous_kilometers = fields.Char(invisible=True,store=False
    control_date = fields.Date()

When kilometers are chaging, I write into previous_kilometers

On save, if previous_kilometers is not equal to kilometers then I write in another table.

  if I use values['previous_kilometers'], i works only when I change kilometers. I case I do not change kilometers but only the control_date then the system does not know  values['previous_kilometers'] and throw a key error.

if I use self.previous_kilometers, then the value is False. The value that I had in the field does not exists.

 

@api.multi
def write(self, values):
    if values['previous_kilometers']:

    if values['previous_kilometers']: 
KeyError: 'previous_kilometers'

I had no success with the examples on the web.

Could you please guide me in the best way to reuse the values in the write method ?

Thank you

Avatar
Discard
Best Answer

Hi,

Change the if statement like this,

if 'previous_kilometers' in values.keys():

This will check whether there is a key previous_kilometers in the values. If  yes, you can get the value from it like this,

if 'previous_kilometers' in values.keys(): 
    print("value is ...", values['previous_kilometers'])

Thanks

Avatar
Discard
Best Answer

Hello there

Always use this style while working with vals

if vals.get('previous_kilometers', False):
    # do stuff

Where False is default value for 'previous_kilometers' if dict doesn't has key 'previous_kilometers'.

Avatar
Discard