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

Odoo中onchange事件触发时给One2many字段赋值失效如何解决

问题原因及修复方案

现有代码的核心问题

  • 缩进语法错误:@api.onchange 装饰器下的方法定义缩进不符合Python规范,会直接触发语法报错,方法定义需要和装饰器保持同级缩进。
  • One2many字段关联逻辑错误:你定义的custom_line_ids反向关联字段填的是product_id,而Odoo原生mrp.production模型的product_id默认关联的是product.product产品模型,如果你当前写代码的模型不是产品模型,这个反向关联是完全错误的,会导致写入的子数据无法和父记录绑定,前端看起来就是赋值没生效。
  • 冗余无效代码:方法内搜索mrp.productions的代码存在两个问题,一是模型名拼写错误(正确模型名为mrp.production,没有末尾的s),二是搜索结果完全没有被使用,属于冗余代码可以直接删除。
  • 关联字段赋值不规范:vals里的product_id等关联字段直接赋值记录集,低版本Odoo不支持该写法,稳妥写法是传入记录的id值。
  • 赋值逻辑默认覆盖原有数据:你当前用[(0, 0, vals)]直接赋值会清空custom_line_ids原有已有的行,如果需要追加新行需要先拼接原有数据。

正确实现步骤

步骤1:修正反向关联字段

首先要保证One2many的关联逻辑正确,假设你当前写代码的模型技术名为custom.parent.model,先给mrp.production新增反向关联字段:

# 在mrp.production的继承模型中新增
from odoo import models, fields, api

class MrpProduction(models.Model):
    _inherit = 'mrp.production'
    
    custom_parent_id = fields.Many2one('custom.parent.model', string='关联父单据')

如果你当前写代码的模型本身就是product.product,可以跳过这一步,直接使用原有product_id作为反向关联字段即可。

步骤2:修正onchange逻辑

# 修正后的One2many字段定义
custom_line_ids = fields.One2many('mrp.production', 'custom_parent_id', string='Custom Line')   

@api.onchange('product_id')
def add_custom_line_ids(self):
    # 产品为空时清空行避免报错
    if not self.product_id:
        self.custom_line_ids = False
        return
    vals = {
        'sequence': self.sequence,
        'name': self.name,
        'product_id': self.product_id.id,
        'date_planned_start': self.date_planned_start,
        'state': self.state,
    }
    # 需要追加新行就用下面的写法,需要覆盖原有行直接赋值 [(0, 0, vals)] 即可
    new_line_list = self.custom_line_ids.ids + [(0, 0, vals)]
    self.custom_line_ids = new_line_list

注意事项

Odoo的onchange逻辑是在前端临时计算的,修改后的数据不会直接写入数据库,只有点击页面保存按钮后才会持久化存储。

内容的提问来源于stack exchange,提问作者Kai Ning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:36:02