我设法得到一个查询工作,总结了父类的所有子行:
subq = db.session.query(Transaction.budget_id, func.sum(Transaction.amount).label("total"), func.count('*').label("count"))
.group_by(Transaction.budget_id).subquery()
return db.session.query(Budget.ID, Budget.name, Budget.start_date, Budget.end_date, Budget.amount, subq.c.total, subq.c.count)
.outerjoin(subq, Budget.ID==subq.c.budget_id)
.order_by(Budget.start_date.desc()).limit(count)
问题是,当预算没有任何事务子类时,它不起作用。它返回None,它会在工作中抛出一个扳手。我希望sum()和count()函数返回0。
答案 0 :(得分:1)
from sqlalchemy.sql.functions import coalesce
...
return db.session.query(Budget.ID,
Budget.name,
Budget.start_date,
Budget.end_date,
Budget.amount,
coalesce(subq.c.total, 0),
coalesce(subq.c.count, 0))
.outerjoin(subq, Budget.ID==subq.c.budget_id)
.order_by(Budget.start_date.desc()).limit(count)