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

Odoo14中Wizard获取active_ids报int对象不可下标错误如何解决

报错原因
  • 第一,Odoo 中Many2many等x2many类型字段不支持直接传入ID列表赋值,必须使用标准ORM操作命令格式,直接传入ID列表或非预期的布尔/整型值都会触发类型错误。
  • 第二,缺少上下文参数校验:未对active_ids的类型做兼容处理,当仅选中单条product.template记录触发向导时,部分场景下active_ids会返回单个整型ID而非列表,底层处理时尝试对整型做下标操作就会触发TypeError: 'int' object is not subscriptable报错。
  • 第三,未校验上下文的active_model,如果向导被其他模型调用会拿到无效ID,引发额外异常。
修复后代码
class Wizard(models.TransientModel):
    _name = "product.wizard"

    product_template_ids = fields.Many2many('product.template')
    
    @api.model
    def default_get(self, fields):
        res = super(Wizard, self).default_get(fields)
        # 校验触发向导的模型是否匹配,避免跨模型调用异常
        if self.env.context.get('active_model') == 'product.template':
            active_ids = self.env.context.get('active_ids', [])
            # 兼容单条记录场景下返回整型的情况
            if not isinstance(active_ids, list):
                active_ids = [active_ids]
            # 使用(6,0,ID列表)的ORM命令给Many2many字段赋值,代表清空现有关联后绑定指定ID的记录
            res['product_template_ids'] = [(6, 0, active_ids)]
        return res
补充说明

x2many字段常用ORM赋值命令:

  • (0, 0, {字段值字典}):新建一条关联记录并绑定
  • (4, 记录ID, 0):追加绑定一条已有记录,不影响现有绑定
  • (6, 0, [ID1, ID2]):清空现有绑定,替换为列表中ID对应的记录,是向导默认值赋值的常用写法

内容的提问来源于stack exchange,提问作者K.ju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 11:36:06