Odoo 10 Qweb:如何遍历销售订单行计算订单总重量?
实现销售订单总重量的聚合乘法计算(Odoo方案)
Hey there! 刚好之前做过类似的需求,给你分享两种靠谱的实现方式,按需选就行:
1. 推荐方案:在销售订单模型中添加计算字段(规范易维护)
这种方式把计算逻辑放在后端模型里,模板只需要直接调用字段,完全符合Odoo的MVC架构,后续扩展和维护都更方便。
步骤:
- 继承
sale.order模型,添加计算字段:
from odoo import models, fields, api class SaleOrder(models.Model): _inherit = 'sale.order' total_weight = fields.Float( string='Total Weight', compute='_compute_total_weight', store=True, # 可选:开启后会把计算结果存到数据库,提升加载速度 readonly=True ) @api.depends('order_line.product_uom_qty', 'order_line.product_id.weight') def _compute_total_weight(self): for order in self: total_weight = 0.0 for line in order.order_line: # 加个判断避免空值报错,比如产品没设置重量的情况 if line.product_id and line.product_uom_qty: total_weight += line.product_uom_qty * line.product_id.weight order.total_weight = total_weight
- 在销售订单的QWeb模板里直接调用这个字段:
<div class="mt-3"> <strong>Total Weight:</strong> <span t-field="o.total_weight" t-options='{"widget": "float", "precision": 2}'/> kg </div>
为什么推荐这个? 逻辑集中在模型层,方便后续加功能(比如单位转换、异常值过滤),而且订单行多的时候性能比模板计算更好。
2. 直接在QWeb模板中计算(快速实现,适合简单场景)
如果不想修改模型,也可以直接在模板里通过循环累加实现,适合临时快速验证需求:
<div class="mt-3"> <strong>Total Weight:</strong> <!-- 初始化总重量为0 --> <t t-set="total_weight" t-value="0.0"/> <!-- 遍历所有订单行累加 --> <t t-foreach="o.order_line" t-as="line"> <t t-set="total_weight" t-value="total_weight + (line.product_uom_qty * (line.product_id.weight or 0.0))"/> </t> <!-- 输出结果,保留两位小数 --> <span t-esc="round(total_weight, 2)"/> kg </div>
⚠️ 注意:这里用line.product_id.weight or 0.0是为了避免产品未设置重量时出现None导致计算错误。如果需要处理单位转换(比如订单行的UOM和产品重量的UOM不一致),这种模板方式会非常繁琐,还是优先选模型字段的方案。
额外提示
如果你的Odoo版本是14及以上,计算字段的depends写法完全没问题;要是需要支持多单位显示,可以在模型里结合product_uom的转换方法来统一单位,比如用line.product_uom._compute_quantity把订单数量转换成产品重量的单位再计算。
内容的提问来源于stack exchange,提问作者M.E.
相关产品推荐
相关产品推荐

