在Flask-SQLAlchemy中进行计数查询

1 投票
1 回答
2058 浏览
提问于 2025-04-17 16:35

我还是对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中是怎么转换成这样的。

1 个回答

3

如果你刚接触SQLAlchemy,建议你先看看这两个教程:对象关系教程SQL表达语言教程,这样你能更好地了解它是怎么工作的。因为你在使用Flask-SQLAlchemy这个扩展,要记住在前面提到的教程中导入的很多名字,可以通过SQLAlchemy类的实例来访问(在Flask-SQLAlchemy的例子中,通常叫db)。当你的SQL查询转换成SQLAlchemy的格式时,可能会像下面这样(未经测试):

# 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'))

撰写回答