2013-02-21 59 views
1

對於SQLAlchemy的工作方式,我仍然感到困惑。截至目前,我有一個看起來像這樣的查詢在Flask-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壽。

回答

3

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

最好的:)謝謝你這... – 2013-02-22 03:43:50