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

Odoo中继承选择字段时不覆盖原字段调整选项顺序的实现方法

调整Odoo继承选择字段的选项顺序

好问题!在Odoo中使用selection_add确实默认会把新选项追加到原有列表的末尾,但要在不覆盖原字段定义的前提下实现自定义顺序,有几个实用的思路,下面逐个说明:

方法1:动态生成选择列表(推荐)

这种方式通过动态获取原字段的选项,然后在指定位置插入新选项,既保留了原字段的继承性,又能灵活控制顺序,而且原字段后续更新时会自动同步。

示例代码:

from odoo import models, fields

class YourInheritedModel(models.Model):
    _inherit = 'original.model'  # 替换为实际的原模型名称

    test_field = fields.Selection(
        selection=lambda self: self._get_test_field_selection(),
        string='Test Field'
    )

    def _get_test_field_selection(self):
        # 获取原模型中test_field的原始选项列表
        original_fields = self.env['original.model'].fields_get(allfields=['test_field'])
        original_selection = original_fields['test_field']['selection']
        
        # 复制原列表并插入新选项到指定位置(这里是索引1,即'A'之后)
        updated_selection = original_selection.copy()
        updated_selection.insert(1, ('b', 'B'))
        
        return updated_selection

方法2:显式定义完整顺序(适合原选项固定的场景)

如果原字段的选项不会发生变化,也可以直接显式写出包含新选项的完整顺序,同时加上inherit=True标记这是继承字段。这种方式简单直接,但原字段更新时需要手动同步。

示例代码:

from odoo import models, fields

class YourInheritedModel(models.Model):
    _inherit = 'original.model'

    test_field = fields.Selection(
        selection=[('a', 'A'), ('b', 'B'), ('c', 'C')],
        string='Test Field',
        inherit=True
    )

方法3:通过fields_get钩子调整顺序

这种方式不需要修改字段定义,而是在Odoo获取字段元数据的环节调整选项顺序,适合需要批量调整多个字段顺序的场景。

示例代码:

from odoo import models

class YourInheritedModel(models.Model):
    _inherit = 'original.model'

    def fields_get(self, allfields=None, attributes=None):
        res = super().fields_get(allfields=allfields, attributes=attributes)
        
        if 'test_field' in res:
            selection = res['test_field']['selection']
            target_option = ('b', 'B')
            
            # 如果新选项已存在,先移除再插入到指定位置
            if target_option in selection:
                selection.remove(target_option)
                # 找到'A'选项的位置,在它后面插入新选项
                a_option_index = next((idx for idx, item in enumerate(selection) if item[0] == 'a'), -1)
                if a_option_index != -1:
                    selection.insert(a_option_index + 1, target_option)
            
            res['test_field']['selection'] = selection
        
        return res

以上几种方法都不需要完全覆盖原字段,各有适用场景,其中方法1的灵活性和可维护性最佳,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:12:46