Sum quantity of same products in python odoo

Viewed 40

i have a variable vals as;

vals = {
    'partner_ids': [80],
    'sh_source': 'PR/G/22/08/26/019,PR/G/22/08/26/018',  
    'purchase_request_id': 27,
    'sh_purchase_agreement_line_ids': [
       (0, 0, {'sh_product_id': 34, 'sh_product_description': 'Ban Motor', 'sh_qty': 4.0, 'request_line_id': 32, 'sh_ordered_qty': 4.0, 'sh_product_uom_id': 1, 'dest_warehouse_id': 1, 'analytic_tag_ids': [1, 2], 'schedule_date': datetime.date(2022, 8, 26)}),
       (0, 0, {'sh_product_id': 34, 'sh_product_description': 'Ban Motor', 'sh_qty': 2.0, 'request_line_id': 31, 'sh_ordered_qty': 2.0, 'sh_product_uom_id': 1, 'dest_warehouse_id': 1, 'analytic_tag_ids': [1, 2], 'schedule_date': datetime.date(2022, 8, 26)})
]}

as shown in code sh_purchase_agreement_line_ids have two records. Now i want same variable as vals but in single by sum sh_qty 4+2=6.

Please guide.

1 Answers

You should post code in a codeblock which is much easier to read.

Simple Loop:

total_qty = 0
for product in vals['sh_purchase_agreement_line_ids']:
    total_qty += product[2]['sh_qty']

It can also be done using list comphrehension to make a one-liner.

total_qty = sum(product[2]['sh_qty'] for product in vals['sh_purchase_agreement_line_ids'])
Related