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

Odoo中按钮传递context无法更新type字段值问题求助

解决向导计算字段type为空的问题

我来帮你排查这个向导计算字段为空的问题,这类问题大多出在context传递或者计算字段的依赖配置上,咱们一步步来:

1. 先确认Context是否真的传过去了

首先得排查最基础的:你的按钮和动作配置里,type参数有没有正确塞进context里。

动作配置示例(XML)

确保你的ir.actions.act_window是这么写的,重点看context字段:

<record id="action_task_make_situation_type_a" model="ir.actions.act_window">
    <field name="name">创建类型A场景</field>
    <field name="res_model">task.make.situation</field>
    <field name="view_mode">form</field>
    <field name="target">new</field>
    <!-- 这里直接传递type参数到context -->
    <field name="context">{'type': 'type_a'}</field>
</record>

按钮配置示例(XML)

如果是按钮直接带context,要注意是否和动作的context冲突:

<!-- 按钮绑定动作,同时传递context -->
<button 
    name="%(action_task_make_situation_type_a)d" 
    string="类型A场景" 
    type="action" 
    context="{'type': 'type_a'}"
/>

注意:如果动作和按钮都定义了context,Odoo会合并两者,但如果键名重复,按钮的context会覆盖动作的。

2. 检查计算字段的定义是否正确

这是最容易踩坑的地方!你的task.make.situation模型里的计算字段,必须正确读取context,并且配置依赖触发条件,否则context变化时字段不会重新计算。

错误的写法(为什么为空?)

如果你的计算函数是这样的,就会出现空值:

@api.depends()  # 没有依赖任何上下文参数
def _compute_type(self):
    for rec in self:
        rec.type = self.env.context.get('type', '')

因为Odoo不知道这个字段依赖context里的type参数,所以不会在context变化时重新计算字段值。

正确的写法

加上@api.depends_context('type'),告诉Odoo这个字段依赖context里的type:

from odoo import models, fields, api

class TaskMakeSituation(models.TransientModel):
    _name = 'task.make.situation'
    _description = '任务场景创建向导'

    type = fields.Char(string='类型', compute='_compute_type', store=False)

    @api.depends_context('type')  # 关键:声明依赖context的type参数
    def _compute_type(self):
        # 可以加个日志排查context内容
        self.env.logger.info(f"当前Context内容:{self.env.context}")
        for rec in self:
            rec.type = self.env.context.get('type', '默认值')

3. 检查向导视图的配置

别忽略视图的问题:

  • 确保视图里的type字段没有设置invisible="1"
  • 计算字段要设置readonly="1"(因为是计算出来的,不能编辑)
  • 字段名拼写要和模型里的完全一致(比如别写成x_type或者Type)

视图示例:

<record id="view_task_make_situation_form" model="ir.ui.view">
    <field name="name">任务场景创建向导表单</field>
    <field name="model">task.make.situation</field>
    <field name="arch" type="xml">
        <form string="创建场景">
            <group>
                <field name="type" readonly="1"/>
                <!-- 其他字段 -->
            </group>
            <footer>
                <button name="action_confirm" string="确认" type="object" class="btn-primary"/>
                <button string="取消" class="btn-secondary" special="cancel"/>
            </footer>
        </form>
    </field>
</record>

4. 终极排查:打印日志确认Context

如果还是不行,就在计算函数里加日志,看看self.env.context里到底有没有type参数。重启Odoo后,点击按钮打开向导,然后查看Odoo的日志,就能知道是context没传过来,还是计算函数的问题了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:45:40