If you are using raw queries, then you just need to merge the data. Something like this should work,
def merge_order_data_and_detail(orders, details):
"""Group details by order_id and merge it in orders."""
# create dictionary key:order_id value:[order_detail_data]
dic = {}
for d in details:
if d['order_id'] not in dic:
dic[d['order_id']] = []
dic[d['order_id']].append(d)
# iterate orders and add details
for o in orders:
if o['order_id'] in dic:
o['order_detail_data'] = dic[o['order_id']]
orders = [
{
"order_id": 1,
"user_id": 5
},
{
"order_id": 2,
"user_id": 50
}
]
details = [
{
"order_detail_id": 1,
"order_id": 1,
"user_id": 5,
"product_id": 202
},
{
"order_detail_id": 2,
"order_id": 1,
"user_id": 5,
"product_id": 203
},
{
"order_detail_id": 3,
"order_id": 2,
"user_id": 50,
"product_id": 402
},
{
"order_detail_id": 4,
"order_id": 2,
"user_id": 50,
"product_id": 403
}
]
merge_order_data_and_detail(orders, details)
print(orders)
Result:
[{'order_id': 1, 'user_id': 5, 'order_detail_data': [{'order_detail_id': 1, 'order_id': 1, 'user_id': 5, 'product_id': 202}, {'order_detail_id': 2, 'order_id': 1, 'user_id': 5, 'product_id': 203}]}, {'order_id': 2, 'user_id': 50, 'order_detail_data': [{'order_detail_id': 3, 'order_id': 2, 'user_id': 50, 'product_id': 402}, {'order_detail_id': 4, 'order_id':
2, 'user_id': 50, 'product_id': 403}]}]
I remove a lot of orders and details attributes just to make simple to test.
I don’t have the whole picture, but should think in using Django models if you are not already using it. It is the way to take advantage of the full potential of the framework.
Hope it helps.
4
solved Django: how to get order_detail_data as per order_id