How to calculate sum values of 1 fields in one2many field in form view odoo then stored in field

247 Views Asked by At

enter image description here

I have field One2many is "order_line_ids" in "order details" and field quantity. Other field is total_qty, i want total_qty equal sum of values quantity in form view.

total_qty=fields.Integer(string="Total Quantity",readonly=True,store=True,
track_visibility='onchange', 
    compute='_compute_total_qty' ) 
@api.depends('order_line_ids.quantity')
def _compute_total_qty(self):
    for record in self:
        rec=sum(line.quantity for line in record.order_line_ids)
        record.update({'total_qty':rec})

My code didn't work. When I change values of quantity, value of total_qty no change. But i click button confirm, value of total_qty stored. Please explain for me .

1

There are 1 best solutions below

0
Ahrimann On

Your issue is caused by the way you're updating the total_qty field inside the for loop. Instead of using record.update(), you should assign a computed value directly to the field total_quantity:

 total_qty = fields.Integer(string="Total Quantity", compute='_compute_total_qty')
   
 @api.depends('order_line_ids.quantity')
 def _compute_total_qty(self):
     for record in self:
         record.total_qty = sum(line.quantity for line in record.order_line_ids)

...so that the computed value of total_qty should update automatically when you change the values of quantity in the order_line_ids