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

Odoo如何根据字段值动态设置XPath中字段的domain?

Odoo根据字段条件动态配置字段Domain的实现方案

问题描述

需要在Odoo中根据字段needs_auth的布尔值,动态调整lots_id字段的Domain:

  • 现有字段定义:
lots_id = fields.Many2one('stock.production.lot', 'Lot/Serial Number')
q_auth = fields.Boolean(related='lot_id.q_auth', string="Quality Auth.")
needs_auth= fields.Boolean("Needs Auth")
  • 当needs_auth == False时,lots_id的Domain为[('product_id','=?', product_id)]
  • 当needs_auth == True时,lots_id的Domain需追加条件:[('product_id','=?', product_id),('q_auth','!=',False)]

询问是否可通过XML实现,若不行则用Python如何实现。


实现方案

1. 仅XML无法实现

Odoo的XML视图定义是静态的,无法根据当前记录的字段值实时动态调整字段的Domain,必须结合Python逻辑实现。

2. Python实现方案

方案一:字段层面动态Domain(Odoo 12+推荐)

直接在lots_id字段定义中使用lambda表达式动态生成Domain,无需修改XML视图:

from odoo import fields, models

class YourModel(models.Model):
    _inherit = 'your.model.name'  # 替换为实际模型名称

    lots_id = fields.Many2one(
        'stock.production.lot', 
        'Lot/Serial Number',
        domain=lambda self: [
            ('product_id', '=?', self.product_id),
            *([] if not self.needs_auth else [('q_auth', '!=', False)])
        ]
    )
    q_auth = fields.Boolean(related='lot_id.q_auth', string="Quality Auth.")
    needs_auth = fields.Boolean("Needs Auth")

说明:当needs_auth或product_id的值变化时,字段的Domain会自动更新,XML视图只需正常渲染lots_id即可。

方案二:onchange方法动态修改Domain(兼容旧版本)

如果使用Odoo 12以下版本,可通过onchange方法触发Domain更新:

from odoo import fields, models, api

class YourModel(models.Model):
    _inherit = 'your.model.name'

    lots_id = fields.Many2one('stock.production.lot', 'Lot/Serial Number')
    q_auth = fields.Boolean(related='lot_id.q_auth', string="Quality Auth.")
    needs_auth = fields.Boolean("Needs Auth")

    @api.onchange('needs_auth', 'product_id')
    def _onchange_needs_auth(self):
        domain = [('product_id', '=?', self.product_id)]
        if self.needs_auth:
            domain.append(('q_auth', '!=', False))
        return {'domain': {'lots_id': domain}}

对应的XML视图配置(无需替换原lot_id):

<field name="lots_id" groups="stock.group_production_lot" context="{'product_id': product_id}"/>
<field name="q_auth" invisible="1"/>

说明:当needs_auth或product_id字段值改变时,会触发该方法,实时更新lots_id的Domain。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:10:16