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

Odoo15向导弹窗如何自动填充瞬态模型中已存储的字段值?

解决瞬态模型向导弹窗自动显示已存储字段值的方法

核心思路

瞬态模型(TransientModel)的记录默认会在会话结束后清理,要让弹窗弹出时自动显示已存储的值,核心是在弹窗初始化阶段,把对应值加载到瞬态模型的字段中,常用两种实现方式:动作上下文传递值、重写默认方法读取值。

具体实现方式

方式一:通过动作上下文传递值

在触发弹窗的按钮动作里,把已存储的cash_collection值通过上下文传递给瞬态模型,初始化时自动赋值:

  1. 定义触发弹窗的按钮,在上下文里指定默认值:
<button name="%(your_module.action_transient_wizard)d" 
        string="打开弹窗" 
        type="action"
        context="{'default_cash_collection': cash_collection}"/>
  • your_module.action_transient_wizard替换为你向导弹窗的动作XML ID
  • default_cash_collection是Odoo的默认值传递规则,前缀default_加字段名,会自动把对应值赋值给瞬态模型的cash_collection字段
  1. 瞬态模型字段保持你已有的定义即可:
from odoo import models, fields

class YourTransientWizard(models.TransientModel):
    _name = 'your.transient.wizard'
    _description = 'Your Transient Wizard'

    cash_collection = fields.Float(string="Cash Collection")

方式二:在瞬态模型的默认方法中读取值

如果需要从关联的持久化模型或数据库中读取已存储的值,可以重写default_get方法:

from odoo import models, fields

class YourTransientWizard(models.TransientModel):
    _name = 'your.transient.wizard'
    _description = 'Your Transient Wizard'

    cash_collection = fields.Float(string="Cash Collection")

    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        # 从关联的主模型读取已存储值,需替换为实际模型名
        active_id = self.env.context.get('active_id')
        if active_id:
            main_record = self.env['your.main.model'].browse(active_id)
            res['cash_collection'] = main_record.cash_collection
        return res
  • your.main.model替换为存储cash_collection值的持久化模型
  • 通过active_id获取触发弹窗的主记录ID,读取对应字段值后赋值给瞬态模型字段

注意事项

  • 瞬态模型记录不会永久存储,每次弹窗都需要重新加载值,上述两种方式都是在弹窗初始化时完成赋值
  • 如果是会话临时存储的值,也可以通过self.env.context或self.env.user的临时属性传递

内容的提问来源于stack exchange,提问作者Abdus Sattar Bhuiyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:57:39