Search code examples
pythonodooodoo-8xml-rpc

How to modify context when calling onchange methods of virtual records?


I am creating a virtual record in order to apply to it the results of several onchange methods. The problem is that for one of this methods, I need to pass a specific context, but this results in losing the virtual record data.

This is the onchange method I am calling:

@api.multi
@api.onchange('product_id')
def onchange_product_id_valued(self):
    _logger.critical('PRODUCT INSIDE ONCHANGE')
    _logger.critical(self.product_id)

The following lines work OK, I can create a virtual record of a stock move, and the logger prints the product OK:

virtual_move = self.env['stock.move'].new({
    ...
    'product_id': product.id,
    ...
})
virtual_move.onchange_product_id_valued()

However, the following lines do not work. When I use with_context to set a specific context, the virtual move attributes are all empty inside the onchange method, so the logger prints an empty recordset of product.product:

virtual_move2 = self.env['stock.move'].new({
    ...
    'product_id': product.id,
    ...
})
virtual_move2.with_context(
    partner_id=xxx,
    picking_type_id=yyy,
    date=zzz,
    pricelist_id=aaa,
    fiscal_position=bbb,
).onchange_product_id_valued()

Why is this happening and how can I send a specific context to the onchange_product_id_valued method without destroying virtual record data?


Solution

  • If someone is wondering how to solve this, the solution is to apply the specific context before executing new() method:

    self = self.with_context(
        partner_id=xxx,
        picking_type_id=yyy,
        date=zzz,
        pricelist_id=aaa,
        fiscal_position=bbb,
    )
    virtual_move2 = self.env['stock.move'].new({
        ...
        'product_id': product.id,
        ...
    })
    virtual_move2.onchange_product_id_valued()