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

Odoo如何在XML继承视图中扩展字段context而非完全替换

实现方式

完全可以通过XML原生实现,无需硬编码原有context参数,Odoo视图继承支持字典类属性的增量合并:

适用版本

Odoo 13及以上版本可直接使用如下XML方案,更低版本需要配合Python代码实现。

XML实现代码

<record id="view_partner_form_custom_inherit" model="ir.ui.view">
    <field name="name">res.partner.form.custom.inherit</field>
    <field name="model">res.partner</field>
    <field name="inherit_id" ref="base.view_partner_form"/>
    <field name="arch" type="xml">
        <xpath expr="//field[@name='my_field']" position="attributes">
            <attribute name="context" operation="add">{'second_context_value': False}</attribute>
        </xpath>
    </field>
</record>

逻辑说明

  • 给attribute标签指定operation="add"参数后,Odoo会识别context是字典类型,自动将新传入的字典和字段原有context合并:已有key会用新值覆盖,未存在的key会保留原有值。
  • 多个模块同时用该方式修改同字段的context时,系统会按模块的依赖顺序逐层合并,不需要手动同步所有已有的context配置。

低版本兼容方案(Odoo 12及以下)

如果使用更早版本,可通过重写fields_view_get方法动态注入context:

from odoo import models, api

class ResPartner(models.Model):
    _inherit = 'res.partner'

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        res = super().fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
        if view_type == 'form':
            # 查找my_field节点
            for node in res['arch'].xpath('//field[@name="my_field"]'):
                # 解析原有context
                existing_context = node.get('context', '{}')
                # 转换为字典合并
                import ast
                context_dict = ast.literal_eval(existing_context)
                context_dict['second_context_value'] = False
                # 回写属性
                node.set('context', str(context_dict))
        return res

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:24:03