1

我仍然对 SQLAlchemy 的工作方式感到困惑。截至目前,我有一个看起来像这样的查询

SELECT cast(a.product_id as bigint) id, cast(count(a.product_id) as bigint) itemsSold, cast(b.product_name as character varying)
    from transaction_details a 
    left join product b
    on a.product_id = b.product_id
    group by a.product_id, b.product_name
    order by itemsSold desc;

我不太确定这是如何在 Flask 中转换的。

4

1 回答 1

3

如果您是 SQLAlchemy 的新手,请阅读对象关系教程SQL 表达式语言教程以熟悉它的工作方式。由于您使用的是 Flask-SQLAlchemy 扩展,请记住,在上述教程的示例中导入的许多名称可以通过SQLAlchemy类的实例(通常db在 Flask-SQLAlchemy 示例中命名)来访问。您的 SQL 查询在转换为 SA 后将如下所示(未经测试):

# Assuming that A and B are mapped objects that point to tables a and b from
# your example.
q = db.session.query(
    db.cast(A.product_id, db.BigInteger),
    db.cast(db.count(A.product_id), db.BigInteger).label('itemsSold'),
    db.cast(B.product_name, db.String)
# If relationship between A and B is configured properly, explicit join
# condition usually is not needed.
).outerjoin(B, A.product_id == B.product_id).\
group_by(A.product_id, B.product_name).\
order_by(db.desc('itemsSold'))
于 2013-02-21T10:11:38.763 回答