如何将字典列表的聚合数据更新到Odoo当前表单的One2many字段
问题根因
你的实现有三个核心问题直接导致关联行不显示:
- 创建
onepos.report.line记录时,完全没有给关联字段report赋值
One2many是虚拟反向字段,本身不存储数据,它的展示逻辑是:筛选所有onepos.report.line模型中,report字段值等于当前主表单记录ID的行,渲染到表单上。你之前创建的行report字段全是空值,自然不会被筛选出来。 - 冗余代码混淆了记录集的绑定关系
你代码里写的report= self.env['onepos.report.line'].search([])拿到的是一个独立的空记录集,用这个记录集create出来的行,没有自动关联到当前正在操作的主表单记录上。 - 聚合逻辑本身存在漏洞
你用来判断POS是否重复的pos_dict根本没有写入键值对,导致判断逻辑永远不触发,销售金额累计结果本身就是错的。
另外提一个不影响显示但不合理的定义:关联行模型里的total字段用Char类型存金额非常不合适,应该用Float类型避免类型转换问题。
修正后的正确实现
第一步:保证字段关联定义正确
你现在写的One2many和Many2one的关联定义本身是没问题的,不需要改动:
- 主模型(
onepos.report)的One2many字段:data = fields.One2many(comodel_name="onepos.report.line", inverse_name="report") - 行模型的Many2one字段:
report = fields.Many2one(comodel_name="onepos.report")
第二步:修正getreport方法的逻辑
核心是创建关联行时,必须把行和当前主表单记录做绑定,去掉冗余的无意义search代码:
from collections import defaultdict def getreport(self): # 先清空当前表单下的旧关联行,避免重复生成历史数据 self.data.unlink() # 遍历所有POS订单做金额聚合 pos_orders = self.env['pos.order'].search([]) # 直接用字典按POS配置名称累计销售额,替代之前有漏洞的判断逻辑 pos_sales_result = defaultdict(float) for order in pos_orders: pos_config_name = order.config_id.name for line in order.lines: pos_sales_result[pos_config_name] += line.price_subtotal_incl # 逐行创建关联行,必须在创建时传入report字段绑定当前主记录ID for pos_name, total_amount in pos_sales_result.items(): self.env['onepos.report.line'].create({ 'pos': pos_name, 'total': total_amount, 'report': self.id # 这行是之前缺失的核心关联逻辑 })
可选优化写法
你也可以不用逐行调用create,直接通过One2many字段的标准赋值操作生成关联行,Odoo会自动处理关联绑定,不容易漏写关联字段:
def getreport(self): self.data.unlink() pos_orders = self.env['pos.order'].search([]) pos_sales_result = defaultdict(float) for order in pos_orders: pos_config_name = order.config_id.name for line in order.lines: pos_sales_result[pos_config_name] += line.price_subtotal_incl # 构造One2many字段支持的创建指令列表 create_commands = [ Command.create({ 'pos': pos_name, 'total': total_amount }) for pos_name, total_amount in pos_sales_result.items() ] # 直接写入One2many字段,Odoo会自动给新创建的行绑定当前主记录 self.write({'data': create_commands})
内容的提问来源于stack exchange,提问作者Mohamed Fouad
相关产品推荐
相关产品推荐

