merge same product id one2many odoo (group by dictionary python) – odoo

input = [
{'product_id': '001', 'location_id': 'NISR', 'qty': 100, 'uom_id': 'roll', 'cost' :50, 'categ_id': 'ALL'},
{'product_id': '001', 'location_id': 'NISR', 'qty': 200, 'uom_id': 'roll', 'cost' :50, 'categ_id': 'ALL'},
{'product_id': '001', 'location_id': 'NISR', 'qty': 300, 'uom_id': 'roll', 'cost' :50, 'categ_id': 'ALL'},
{'product_id': '002', 'location_id': 'NISR', 'qty': 400, 'uom_id': 'roll', 'cost' :20, 'categ_id': 'ALL/SUB'},
{'product_id': '002', 'location_id': 'NISR', 'qty': 500, 'uom_id': 'roll', 'cost' :20, 'categ_id': 'ALL/SUB'},
{'product_id': '002', 'location_id': 'NISR', 'qty': 600, 'uom_id': 'roll', 'cost' :20, 'categ_id': 'ALL/SUB'},
{'product_id': '003', 'location_id': 'NISR', 'qty': 700, 'uom_id': 'roll', 'cost' :30, 'categ_id': 'ALL'},

grouper = itemgetter("product_id", "location_id", "uom_id" ,"cost")
result = []
for key, grp in groupby(sorted(input, key = grouper), grouper):
    temp_dict = dict(zip(["product_id", "location_id","uom_id", "cost"], key))
    temp_dict["categ_id"]=  (list(set(item["categ_id"] for item in grp))[0])
    temp_dict["qty"] = sum(item["qty"] for item in grp)
    temp_dict["amount"] =  temp_dict["cost"] * temp_dict["qty"]
from pprint import pprint

[{'amount': 0,
  'categ_id': 'ALL',
  'cost': 50,
  'location_id': 'NISR',
  'product_id': '001',
  'qty': 0,
  'uom_id': 'roll'},
 {'amount': 0,
  'categ_id': 'ALL/SUB',
  'cost': 20,
  'location_id': 'NISR',
  'product_id': '002',
  'qty': 0,
  'uom_id': 'roll'},
 {'amount': 0,
  'categ_id': 'ALL',
  'cost': 30,
  'location_id': 'NISR',
  'product_id': '003',
  'qty': 0,
  'uom_id': 'roll'}]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.