Search code examples
pythonpython-2.7odoo-8odoo

How to get id as integer from on_change method?


I want to select distinct values with an sql query, for that I need id as integer.

My code is:

@api.onchange('qty')
def _on_change_name(self):
    logging.warning(self.id)

The printed id is <openerp.models.NewId object at 0x7fc37d880490>

How can I get integer from this id ?


Solution

  • When you are creating a new record in a model with computed fields or in a onchange method, the records of the recordset will be in memory only. At that time the id of the record will be a dummy ids of type openerp.models.NewId

    So if you need to use the record id in your code (e.g. for a sql query) you should check if it is available:

    if isinstance(current_record.id, models.NewId):
        # do your stuff
    

    Update. Zoellner has a better answer here

    Take a look into onchange() line 4971 and following. Odoo is creating a new record in cache/memory and will later, after the onchange is done, update the own cache with the provided data.

    If you really need the ID or other fields use <record>._origin.<field>.

    Note: Don't use api.one decorator on onchange methods. They are triggered on singleton records anyway.