I am trying to make make the subtotal column field editable and compute the unit price field by writing an onchange function for unit price that will be calculated by dividing subtotal by quantity.
This is my code so far:
class custom_unit_price(models.Model):
_inherit = 'purchase.order.line'
subtotal = fields.Float(compute='_compute_subtotal', store=True)
price_unit = fields.Float(compute='_compute_unit_price', inverse='_set_unit_price')
@api.depends('product_qty', 'price_unit', 'taxes_id')
def _compute_subtotal(self):
for line in self:
taxes = line.taxes_id.compute_all(line.price_unit, line.order_id.currency_id, line.product_qty, line.product_id, line.order_id.partner_id)
line.subtotal = taxes['total_excluded']
def _inverse_subtotal(self):
for line in self:
if line.product_qty != 0:
line.price_unit = line.subtotal / line.product_qty
else:
line.price_unit = 0.0
@api.depends('subtotal', 'product_qty')
def _compute_unit_price(self):
for line in self:
if line.product_qty != 0:
line.price_unit = line.subtotal / line.product_qty
else:
line.price_unit = 0.0
def _set_unit_price(self):
for line in self:
line.subtotal = line.price_unit * line.product_qty
@api.onchange('subtotal')
def _onchange_subtotal(self):
if self.product_qty != 0:
self.price_unit = self.subtotal / self.product_qty
else:
self.price_unit = 0.0
@api.onchange('product_qty', 'price_unit')
def _onchange_qty_or_price(self):
self.subtotal = self.product_qty * self.price_unit
When I enter any amount in subtotal field, nothing happens. It reverts back to its original state (unit price * quantity). I want the unit price field to change when there is change in subtotal field or product quantity field.
Thank you.