如何使用sqlalchemy对连接查询中的列求和?

时间:2017-09-28 07:54:57

标签: python flask sqlalchemy

我想加入两个表,其中user_id作为公共字段,并在表2中加上2个字段。在许多尝试中,有效的查询是:

   data = db.session.query(Subscription.units, Subscription.subscription, Subscription.user_id, func.sum(Subscription.units).label('units'), func.sum(Subscription.subscription).label('sub')).filter(user_id==2).group_by(Subscription.user_id, Subscription.units, Subscription.subscription)

当我尝试使用以下代码在模板中显示它时:

{% for item in data %}
<div>
You have invested <span class="green"> Euro  {{ item.sub }} </span> and you own <span class="blue"> {{ item.units }} </span> shares.
</div>
{% endfor %}

以令人沮丧和幽默的方式迭代此user_id的所有条目并将其全部打印出来,如下所示:

You have invested Euro 0.0 and you own 0.0 shares.
You have invested Euro 5000.0 and you own 5.0 shares.
You have invested Euro 3000.0 and you own 2.63 shares.
You have invested Euro 0.0 and you own 0.0 shares. 

总结没有发生,我只想在视图中的一行说:

You have invested Euro 8000.0 and you own 7.63 shares.

错误是由错误的查询或模板中的错误循环引起的?

0 个答案:

没有答案