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

Odoo13中根据父模型m2o字段值过滤子模型对应m2o字段值域问题

错误原因

你的实现存在3个核心问题导致不生效:

  1. @api.onchange 触发时self仅包含当前编辑的单条父记录,不需要循环遍历,循环逻辑多余
  2. Domain过滤条件错误:你要过滤的是account.analytic.account模型的记录,匹配字段应为模型主键id,而非不存在的analytic_account_id字段
  3. Odoo不支持在父模型的onchange返回值中用one2many字段.子字段的嵌套格式给子模型字段设置domain,该写法规则不支持

推荐实现方案

无需依赖onchange,通过上下文传值+字段约束即可实现需求,同时保证前后端校验一致:

1. 调整子模型字段定义

from odoo.exceptions import ValidationError

class AdditionalServicesLine(models.Model):
    _name = "additional.service.line"
    _description = "Additional services"

    waybill_id = fields.Many2one('logistic.logistic', string='Additional Services Entry')
    analytic_account_id = fields.Many2one(
        'account.analytic.account', 
        string='Analytic Account', 
        index=True,
        required=True,
        # 从上下文读取父模型传递的分析账户ID过滤可选值
        domain="[('id', '=', context.get('parent_analytic_id'))]",
        # 默认自动带入父模型的分析账户,无需手动选择
        default=lambda self: self.env.context.get('parent_analytic_id')
    )

    # 增加后端校验,防止绕过前端限制修改
    @api.constrains('analytic_account_id', 'waybill_id')
    def _check_analytic_match(self):
        for line in self:
            if line.waybill_id and line.analytic_account_id != line.waybill_id.analytic_account_id:
                raise ValidationError("子服务行的分析账户必须与父运单的分析账户保持一致")

2. 调整父模型form视图中one2many字段的配置

在logistic.logistic的form视图里,给additional_services_ids字段传递上下文:

<field 
    name="additional_services_ids" 
    context="{'parent_analytic_id': analytic_account_id}"
>
    <!-- 原有one2many的内嵌视图代码保持不变 -->
</field>

3. 父模型无需保留原有onchange方法,直接删除即可

该方案实现后,子模型的分析账户可选值会自动跟随父模型选中值过滤,且默认自动填充,后端也有强制校验保证数据一致性。


内容的提问来源于stack exchange,提问作者SH EB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:06:05