我仍然对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类的实例(通常在Flask-SQLAlchemy示例中命名为db)访问在上述教程的示例中导入的许多名称。 )。您的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'))

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

10-14 13:42
查看更多