【发布时间】:2021-02-08 04:41:14
【问题描述】:
我正在尝试创建一个基本 API,我有一个名为 orders 的表和另一个名为 order_lines 的表,其中每个订购的产品都有一行,其中一个名为 order_id 的字段对应于订单。在执行 GET 请求时,如何将订单作为父订单并将其中的每个 order_lines 记录作为子数组?我不确定是否需要以某种方式在 SQL 中执行此操作,或者是否可以在 Python 中轻松执行此操作。我只需要大致了解如何提取和构建这些数据。
我的 API GET 请求如下所示:
@app.route('/api/v1/ordertest', methods=['GET'])
def orders_test2():
# try:
if request.method == 'GET':
query_parameters = request.args
id = query_parameters.get('id')
customer_id = query_parameters.get('customer_id')
query = '''
SELECT
o.*,
ol.product_id,
p.name,
ol.quantity,
p.price as price,
round((p.price * ol.quantity), 2) as total_price
FROM orders o
join order_lines ol
on o.id = ol.order_id
join products p
on ol.product_id = p.id
WHERE o.
'''
to_filter = []
if id:
query += 'id=? AND'
to_filter.append(id)
if customer_id:
query += 'customer_id=? AND'
to_filter.append(customer_id)
if not (id or customer_id):
return page_not_found(404)
query = query[:-4] + ';'
conn = sqlite3.connect(db)
conn.row_factory = dict_factory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
执行/api/v1/ordertest?id=1 会返回我想要的所有数据,但它包含每个产品对象中列出的订单表中的信息。
[
{
"created_at": "2020-11-12 00:08:32",
"customer_id": 1,
"id": 1,
"name": "plum",
"price": 0.3,
"product_id": 4,
"quantity": 2,
"status": "delivered",
"total_price": 0.6,
"updated_at": "2021-02-05 18:41:20"
},
{
"created_at": "2020-11-12 00:08:32",
"customer_id": 1,
"id": 1,
"name": "salmon",
"price": 6.76,
"product_id": 20,
"quantity": 4,
"status": "delivered",
"total_price": 27.04,
"updated_at": "2021-02-05 18:41:20"
},
{
"created_at": "2020-11-12 00:08:32",
"customer_id": 1,
"id": 1,
"name": "mint chocolate bar",
"price": 2.01,
"product_id": 30,
"quantity": 3,
"status": "delivered",
"total_price": 6.03,
"updated_at": "2021-02-05 18:41:20"
}
]
但是,我希望数据看起来像这样,其中具有匹配 order_id 的每个 order_lines 行都位于主对象内:
[
{
"created_at": "2020-11-12 00:08:32",
"customer_id": 1,
"id": 1,
"status": "delivered",
"updated_at": "2021-02-05 18:41:20",
"products":
{
"name": "plum",
"price": 0.3,
"product_id": 4,
"quantity": 2,
"total_price": 0.6
},
{
"name": "salmon",
"price": 6.76,
"product_id": 20,
"quantity": 4,
"total_price": 27.04
},
{
"name": "mint chocolate bar",
"price": 2.01,
"product_id": 30,
"quantity": 3,
"total_price": 6.03
}
}
]
【问题讨论】:
-
考虑使用像SQLAlchemy这样的ORM
-
在生产中,您通常会写出每个列名(而不是使用 *),因为它用于文档,并确保代码不会仅仅因为将新列添加到您使用的表中而改变行为.如果主键和副键使用相同的名称,则可以使用自然关节,这意味着您不需要指定所有样板关节条件。 IE。而不是 orders.id 使用 orders.order_id 作为你的主键。