Om du använder råfrågor behöver du bara slå samman data. Något sådant här borde fungera,
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}]}]
Jag tar bort många beställningar och detaljattribut bara för att göra det enkelt att testa.
Jag har inte hela bilden, men bör tänka på att använda Django-modeller om du inte redan använder det. Det är sättet att dra nytta av ramverkets fulla potential.
Hoppas det hjälper.