Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Django:como obter order_detail_data conforme order_id


Se você estiver usando consultas brutas, basta mesclar os dados. Algo assim deve funcionar,
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)

Resultado:
[{'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}]}]

Eu removo muitos atributos de pedidos e detalhes apenas para simplificar o teste.

Eu não tenho a imagem completa, mas deveria pensar em usar modelos do Django se você ainda não estiver usando. É a maneira de aproveitar todo o potencial do framework.

Espero que ajude.