Odoo14计算lead_product_ids总价时报crm.lead.product无法转整数错误
问题排查与解决方案
错误根因定位
- 直接报错点:
for all in range(i)语句中,i是crm.lead.product模型的记录实例,不是整数,range()函数要求传入整数参数,因此触发类型错误。 - 其他逻辑错误:
- 多余的嵌套循环:外层已经遍历
rec.lead_product_ids拿到每一条产品记录,不需要再套一层range(i)的循环 sum(total)用法错误:total是单条产品的金额数值,不是可迭代对象,直接累加即可,不需要用sum()- 赋值位置错误:在循环内部给
rec.total_qty_price_unit赋值,会导致每次循环都覆盖之前的计算结果,最终只会保留最后一条产品的金额
- 多余的嵌套循环:外层已经遍历
修复后代码
常规遍历写法:
@api.depends('lead_product_ids.qty', 'lead_product_ids.price_unit') def _compute_total_price(self): for rec in self: total_amount = 0 # 直接遍历所有关联产品记录即可 for product_line in rec.lead_product_ids: # 累加单条产品的金额 total_amount += product_line.qty * product_line.price_unit # 遍历完所有产品后再赋值 rec.total_qty_price_unit = total_amount or 0
更简洁的Odoo记录集内置写法:
@api.depends('lead_product_ids.qty', 'lead_product_ids.price_unit') def _compute_total_price(self): for rec in self: rec.total_qty_price_unit = sum(line.qty * line.price_unit for line in rec.lead_product_ids) or 0
内容的提问来源于stack exchange,提问作者Jaymezon
相关产品推荐
相关产品推荐

