Hvis du bruger rå forespørgsler, skal du blot flette dataene. Sådan noget burde virke,
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)
Resultat:
[{'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}]}]
Jeg fjerner en masse ordrer og detaljer attributter bare for at gøre det nemt at teste.
Jeg har ikke hele billedet, men bør tænke i at bruge Django-modeller, hvis du ikke allerede bruger det. Det er måden at udnytte rammens fulde potentiale på.
Håber det hjælper.