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

解决Odoo中One2many组件新建记录时的ValueError错误

问题:Odoo 14中One2many添加记录时触发ValueError错误

我在product.template模型中添加了一个简单的One2many字段,并在product.template表单视图中配置了one2many组件。组件能正常显示,但点击“Add a line”按钮新建记录时,触发错误:

ValueError: Invalid field 'product_variant_count' on model '_unknown'

奇怪的是,我的代码中并未使用错误信息里提到的product_variant_count字段。环境为Odoo-14,Python 3.9。

相关代码

1. product.template.substitute模型

class ProductTemplateSubstitute(models.Model):
    _name = "product.template.substitute"
    _description = "Product Substitute"
    _rec_name = "manufacturer_part_number"

    manufacturer_part_number = fields.Char(string="Manufacturer Part Number", required=True)
    product_id = fields.Many2one(string="Product", required=True)

    _sql_constraints = [
        (
            "unique_manufacturer_part_number",
            "unique (manufacturer_part_number)",
            "Manufacturer part number already exists!",
        )
    ]

2. product.template模型继承

class ProductTemplateInherited(models.Model):
    _inherit = "product.template"

    product_substitute_ids = fields.One2many(
        string="Product Substitutes", comodel_name="product.template.substitute", inverse_name="product_id"
    )

3. product.template视图配置

<odoo>
    <record id="product_template_form_view" model="ir.ui.view">
        <field name="name">product.template.form.view.inherit.vendor.eshop.connector</field>
        <field name="model">product.template</field>
        <field name="inherit_id" ref="product.product_template_form_view"/>
        <field name="arch" type="xml">
            <group name="bill" position="after">
                <group name="product_substitutes" string="Substitutes">
                    <field name="product_substitute_ids" widget="one2many" nolabel="1">
                    <tree editable="bottom">
                        <field name="manufacturer_part_number"/>
                    </tree>
                </field>
                </group>
            </group>
        </field>
    </record>
</odoo>
解决方案

错误根源是product.template.substitute模型中的product_id字段(Many2one类型)未指定comodel_name参数,导致Odoo无法识别关联的目标模型,进而触发了非预期的字段错误。修正后的代码如下:

# 错误写法
product_id = fields.Many2one(string="Product", required=True)
# 正确写法
product_id = fields.Many2one(string="Product", comodel_name="product.template", required=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:10:28