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

Odoo 18中如何让两个关联字段根据状态实现不同只读行为?

问题描述

我定义了以下字段:

qty_request = fields.Float('Qty Request')
product_qty = fields.Float('Product Quantity',
                           digits = 'Product Unit of Measure',
                           related = "qty_request",
                           store = True )

实现了用户在qty_request输入值时,product_qty自动填充的效果。现在需要满足以下权限控制:

  • qty_request仅在draft(草稿)状态可编辑,confirm(确认)状态下只读
  • product_qty仅在confirm状态可编辑,draft状态下只读

我在视图中配置了如下代码:

<field name="qty_request" readonly="state != 'draft'"/>
<field name="product_qty" string="Quantity" readonly="state != 'confirm'"/>

但product_qty的只读行为始终跟随qty_request,推测是因为product_qty设置了related关联字段导致的,请问该如何解决?

解决方案

核心问题是**related字段本质是原字段的引用,并非独立字段**——它的编辑权限会继承原字段属性,且修改related字段本质就是修改原字段,完全不符合你需要的"分状态独立控制"需求。

解决思路是将product_qty改为独立字段,通过业务逻辑实现不同状态下的数值同步:

1. 修改模型字段定义

去掉product_qty的related属性,改为普通存储字段:

qty_request = fields.Float('Qty Request')
product_qty = fields.Float('Product Quantity',
                           digits='Product Unit of Measure',
                           store=True)

2. 实现状态同步逻辑

通过onchange方法在不同状态下自动同步数值:

@api.onchange('qty_request')
def _onchange_qty_request(self):
    # 草稿状态下,修改qty_request自动同步到product_qty
    if self.state == 'draft':
        self.product_qty = self.qty_request

@api.onchange('product_qty')
def _onchange_product_qty(self):
    # 确认状态下,修改product_qty自动同步回qty_request(根据业务需求可选)
    if self.state == 'confirm':
        self.qty_request = self.product_qty

如果需要更严格的数值同步(比如草稿状态强制product_qty等于qty_request),可以改用计算字段实现:

qty_request = fields.Float('Qty Request')
product_qty = fields.Float('Product Quantity',
                           digits='Product Unit of Measure',
                           compute='_compute_product_qty',
                           inverse='_inverse_product_qty',
                           store=True)

@api.depends('qty_request', 'state')
def _compute_product_qty(self):
    for record in self:
        if record.state == 'draft':
            record.product_qty = record.qty_request
        # 确认状态下保持现有值,不自动同步

def _inverse_product_qty(self):
    for record in self:
        if record.state == 'confirm':
            record.qty_request = record.product_qty

3. 保留原视图配置

视图层的readonly配置无需修改,现在product_qty是独立字段,权限控制会正常生效:

<field name="qty_request" readonly="state != 'draft'"/>
<field name="product_qty" string="Quantity" readonly="state != 'confirm'"/>

内容的提问来源于stack exchange,提问作者Osama bin Mirza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:07:04