Search code examples
odooodoo-10odoo-9

Odoo onchange not working correctly


I'm inherit purchase.order.line and try change value in field. For product_qty I can change value but for price_unit I can't change value.

My custom .py file:

class PurchaseOrderLine(models.Model):

_inherit = 'purchase.order.line'


@api.onchange('product_id')
def my_fucn(self):
    for rec in self:
        rec.product_qty = 10  #WORKING
        rec.price_unit = 1    #NOT WORKING

Maybe is problem because in original purcahase.py odoo file also have @api.onchange('product_id').

Any solution?


Solution

  • You can't predict which onchange method will be triggered first or last, but the original onchange method for product_id changes in purchase.order.line is setting the price_unit field, but not the product_qty field.

    So it seems your method is called before the other one, because price_unit is overwritten. You can check that by debugging both methods.

    What to do now? I would prefer the extension of the original method:

    @api.onchange('product_id')
    def the_original_method(self):
        res = super(PurchaseOrderLine, self).the_original_method()
        # your logic here
        return res
    

    In your case a product_qty change will trigger another onchange event. Always have in mind, that field changes can trigger onchange events and field recomputations.

    Try to extend both methods:

    @api.onchange('product_id')
    def onchange_product_id(self):
        res = super(PurchaseOrderLine, self).onchange_product_id()
        # your logic here
        for rec in self:
            rec.product_qty = 10  # will trigger _onchange_quantity() on return
    
        return res
    
    @api.onchange('product_qty', 'product_uom')
    def _onchange_quantity(self):
        res = super(PurchaseOrderLine, self)._onchange_quantity()
        # your logic here
        for rec in self:
            rec.price_unit = 1.0
    
        return res