我有以下代码:

    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对象,该对象只返回不同行的a计数。

最佳答案

假设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)

关于python - SQLAlchemy选择不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28372848/

10-12 13:42