2015-02-06 61 views
2

我有以下代碼:SQLAlchemy的選擇不同

session = Session() 
    query = session.query('count').from_statement(
     """ 
      SELECT COUNT(DISTINCT autoresponder.campaign_id) as count 
      FROM autoresponder 
      WHERE autoresponder.account_id=:account_id AND autoresponder.is_active='t' 
     """ 
    ).params(account_id=account_id).all() 

    print query[0].count 

但我想了解SQLAlchemy的更好,希望上面的SQL語句轉換成SQLAlchemy的ORM的對象,只是返回不同的行計數。

回答

3

假設Autoresponder是映射類:

class Autoresponder(Base): 
    __tablename__ = 'autoresponder' 
    id = Column(Integer, primary_key=True) 
    account_id = Column(Integer, ForeignKey("account.id")) 
    # account_id = Column(Integer) # @note: probably a ForeignKey("account.id")) 
    campaign_id = Column(Integer) # @note: probably as well a FK 
    is_active = Column(Boolean) 

下面的查詢應該這樣做:

from sqlalchemy import func 
cnt = (session.query(func.count(Autoresponder.campaign_id.distinct()).label("count")) 
    .filter(Autoresponder.account_id == account_id) 
    .filter(Autoresponder.is_active == True) 
).scalar() 
print(cnt)