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

如何保存用户在Odoo计算字段中手动输入的值?

解决Odoo计算字段手动输入值被覆盖的问题

问题根源

你的custom_field是计算字段,每次tax_totals_json或date_order变更,或是保存记录时,_compute_test方法都会重新执行,直接覆盖手动输入的值。虽然配置了inverse方法,但你没有在里面实现存储逻辑,导致手动输入的值无法持久化,最终被自动计算结果覆盖。

解决方案

新增一个存储字段专门保存手动输入的值,让计算字段优先读取手动输入值;无手动输入时,再执行自动计算逻辑。具体修改如下:

1. 修改Python代码

import json
import random
from odoo import models, fields, api

class SaleOrderInherited(models.Model):
    _inherit = 'sale.order' 

    # 新增存储字段,用于持久化手动输入的值
    custom_field_manual = fields.Char(string='Test Manual')
    # 计算字段:优先用手动输入值,无输入时自动计算
    custom_field = fields.Char(string='Test',
                               compute="_compute_test", 
                               inverse="_inverse_compute_test")

    @api.depends('tax_totals_json', 'date_order', 'custom_field_manual')
    def _compute_test(self):
        for record in self:
            # 优先读取手动输入的持久化值
            if record.custom_field_manual:
                record.custom_field = record.custom_field_manual
            else:
                # 原有自动计算逻辑
                total = json.loads(record.tax_totals_json)['amount_total']
                if int(total) == 0:
                    record.custom_field = str(random.randint(1, 1000))
                else:
                    record.custom_field = f"{total} - {record.date_order}"

    def _inverse_compute_test(self):
        for record in self:
            # 将手动输入的计算字段值同步到存储字段
            record.custom_field_manual = record.custom_field

2. 视图代码无需修改

你的XML视图保持原样即可,用户依然操作custom_field字段,体验完全不受影响。

核心逻辑说明

  • custom_field_manual是存储字段,会将手动输入的值写入数据库,不会被计算方法覆盖。
  • 计算方法的depends参数新增custom_field_manual,确保手动输入值变更时,计算字段能同步更新。
  • inverse方法负责把用户在custom_field的输入值同步到存储字段,实现持久化。

修改后,手动输入的值会被永久保存,不会再被自动计算结果覆盖;若清空手动输入值,字段会自动恢复到计算状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:20:31