You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask-SQLAlchemy一对多关系分组:按支付类型汇总金额

SQLAlchemy实现按付款类型分组求和

针对你的需求,这里提供几种适配Flask-SQLAlchemy的实现方式:

1. 单个订单的付款分组统计

如果已获取到某个Venda实例,可直接查询其关联的VendaPagamento记录,按tipo分组并求和valor:

from sqlalchemy import func

# 假设已获取目标订单实例
venda = Venda.query.get(1)

# 执行分组求和查询
payment_stats = db.session.query(
    VendaPagamento.tipo,
    func.sum(VendaPagamento.valor).label('total')
).filter(VendaPagamento.venda_id == venda.id)\
 .group_by(VendaPagamento.tipo)\
 .all()

返回的payment_stats是元组列表,每个元素格式为(tipo, total),可直接在模板中遍历展示:

{% for tipo, total in payment_stats %}
    <div>付款类型 {{ tipo }}:总计 {{ total }}</div>
{% endfor %}

2. 给Venda模型添加动态属性(推荐)

为了在模板中更便捷调用,可给Venda类添加@property属性,自动计算当前订单的付款分组统计:

from sqlalchemy import func

class Venda(db.Model):
    # ... 保留原有模型字段 ...

    @property
    def payment_summary(self):
        return db.session.query(
            VendaPagamento.tipo,
            func.sum(VendaPagamento.valor).label('total')
        ).filter(VendaPagamento.venda_id == self.id)\
         .group_by(VendaPagamento.tipo)\
         .all()

之后在模板中无需额外查询,直接通过订单实例访问:

{% for tipo, total in venda.payment_summary %}
    <p>类型 {{ tipo }}:{{ total }}</p>
{% endfor %}

3. 批量查询所有订单的分组统计

如果需要一次性获取所有订单的付款分组数据,可通过关联查询实现:

from sqlalchemy import func

all_payment_stats = db.session.query(
    Venda.id,
    VendaPagamento.tipo,
    func.sum(VendaPagamento.valor).label('total')
).join(Venda.pagamentos)\
 .group_by(Venda.id, VendaPagamento.tipo)\
 .all()

返回结果格式为(venda_id, tipo, total),可根据订单ID整理为字典结构方便使用:

# 整理为 {venda_id: {tipo: total, ...}, ...}
stats_dict = {}
for venda_id, tipo, total in all_payment_stats:
    if venda_id not in stats_dict:
        stats_dict[venda_id] = {}
    stats_dict[venda_id][tipo] = total

内容的提问来源于stack exchange,提问作者Rodrigo P.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:40:22