在Flask-SQLAlchemy中选择with count

时间:2013-02-21 05:14:09

标签: python sqlalchemy flask flask-sqlalchemy

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

1 个答案:

答案 0 :(得分:3)

如果您是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'))