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

Odoo 14:如何基于其他字段动态填充选择字段?

问题分析

你遇到的核心问题是:Odoo的Selection字段默认是模型级别的配置,所有记录共享同一套选项列表,无法直接基于单个记录的字段值生成专属选项。你的代码中self为空记录集(stock.move.line()),是因为Odoo在加载模型或视图时就会调用selection绑定的函数,此时还未关联具体的记录实例,自然无法获取到当前记录的A、B字段值。

解决方案

要实现每个记录的选择选项基于自身A、B字段动态生成,需要改用Char字段配合selection组件,并通过onchange方法实时更新选项:

1. 模型代码修改

from odoo import models, fields, api

class StockMoveLine(models.Model):
    _inherit = 'stock.move.line'

    A = fields.Char(string="A Field")
    B = fields.Char(string="B Field")
    selection_field = fields.Char(string="Selection Field")

    @api.onchange('A', 'B')
    def _onchange_update_selection_options(self):
        # 收集当前记录的有效选项
        options = []
        if self.A:
            options.append((self.A, 'Yes'))
        if self.B:
            options.append((self.B, 'No'))
        
        # 清空无效的现有选择(如果A/B变化后原选择不在新选项中)
        if self.selection_field not in [opt[0] for opt in options]:
            self.selection_field = False
        
        # 返回选项更新到视图
        return {
            'options': {
                'selection_field': options
            }
        }

2. 视图代码修改(继承原表单视图)

<odoo>
    <record id="view_stock_move_line_form_inherit" model="ir.ui.view">
        <field name="name">stock.move.line.form.inherit</field>
        <field name="model">stock.move.line</field>
        <field name="inherit_id" ref="stock.view_move_line_form"/>
        <field name="arch" type="xml">
            <!-- 将字段添加到合适位置,示例放在location_id字段之后 -->
            <xpath expr="//field[@name='location_id']" position="after">
                <field name="A"/>
                <field name="B"/>
                <field name="selection_field" widget="selection"/>
            </xpath>
        </field>
    </record>
</odoo>
效果说明
  • 当A或B字段值变化时,onchange方法会实时更新selection_field的可选选项;
  • 如果原有选择不在新生成的选项列表中,会自动清空该字段,避免无效值留存;
  • 每个记录的选择选项完全基于自身的A、B字段值生成,满足动态定制需求。

内容的提问来源于stack exchange,提问作者Jorge Ledesma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:35:13