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

如何为Odoo模型添加公司选择字段并在函数中调用选中值?

问题1:实现可选择公司的Selection字段

不能直接通过related将Many2one字段关联到Selection字段,两者数据类型不匹配。正确做法是通过动态selection方法加载系统中所有公司作为选项:

from odoo import models, fields

class YourModel(models.Model):
    _name = 'your.model.name'
    _description = '自定义模型'

    def _get_company_options(self):
        # 查询所有公司,返回(id, 公司名称)的元组列表作为Selection选项
        company_list = self.env['res.company'].search([])
        return [(comp.id, comp.name) for comp in company_list]

    company_selection = fields.Selection(
        selection='_get_company_options',
        string="选择公司",
        readonly=False
    )

如果需要同时维护Many2one和Selection字段(双向同步),可以用计算字段实现联动:

res_comp = fields.Many2one(comodel_name="res.company", string="公司")
company_selection = fields.Selection(
    selection='_get_company_options',
    string="选择公司",
    compute='_sync_company_selection',
    inverse='_sync_res_comp',
    store=True
)

def _sync_company_selection(self):
    for rec in self:
        # 将Many2one的ID转为字符串,匹配Selection的键类型
        rec.company_selection = str(rec.res_comp.id) if rec.res_comp else False

def _sync_res_comp(self):
    for rec in self:
        if rec.company_selection:
            rec.res_comp = int(rec.company_selection)
        else:
            rec.res_comp = False
问题2:在函数中获取选中的公司值

你之前的代码错误在于直接访问asd(全局变量),而非模型记录的字段值。另外用related="res_comp.name"关联Selection字段本身逻辑错误,Selection需要键值对而非纯字符串。

基于上面的Selection字段实现,正确获取值的代码:

def test_func(self):
    # Odoo中self是记录集,需遍历处理每条记录
    for rec in self:
        selected_company_id = rec.company_selection
        if selected_company_id:
            # 通过ID查询公司记录,获取名称等信息
            company = self.env['res.company'].browse(int(selected_company_id))
            print(f"选中的公司:{company.name},ID:{company.id}")
        else:
            print("未选择任何公司")

如果直接用Many2one字段,代码更简洁:

res_comp = fields.Many2one(comodel_name="res.company", string="TEST")

def test_func(self):
    for rec in self:
        if rec.res_comp:
            print(f"选中的公司名称:{rec.res_comp.name}")
            print(f"选中的公司ID:{rec.res_comp.id}")
        else:
            print("未选择公司")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:15:41