Django: How To Get Order_detail_data As Per Order_id
class Order_ListAPIView(APIView): def get(self,request,format=None): totalData=[] if request.method == 'GET': cur,conn = connection() or
Solution 1:
If you are using raw queries, then you just need to merge the data. Something like this should work,
defmerge_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'] notin dic:
dic[d['order_id']] = []
dic[d['order_id']].append(d)
# iterate orders and add detailsfor 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.
Post a Comment for "Django: How To Get Order_detail_data As Per Order_id"