gpt4 book ai didi

python - SQLAlchemy 选择不同的

转载 作者:行者123 更新时间:2023-11-29 12:05:00 25 4
gpt4 key购买 nike

我有以下代码:

    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 对象。

最佳答案

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com