gpt4 book ai didi

python - 在 Flask-SQLAlchemy 中选择计数

转载 作者:行者123 更新时间:2023-11-30 23:37:56 25 4
gpt4 key购买 nike

我仍然对 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 中转换的。

最佳答案

如果您是 SQLAlchemy 的新手,请阅读 Object Relational TutorialSQL Expression Language Tutorial熟悉它的工作方式。由于您使用的是 Flask-SQLAlchemy 扩展,请记住,在上述教程的示例中导入的许多名称可以通过 SQLAlchemy 类的实例(通常名为 db Flask-SQLAlchemy 示例中)。当转换为 SA 时,您的 SQL 查询将如下所示(未经测试):

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

关于python - 在 Flask-SQLAlchemy 中选择计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14995026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com