Odoo 10中如何在表单视图显示many2one字段全部记录而非下拉列表
在Odoo 10中展示Many2One关联的全部记录(替代下拉列表)
嘿,这个需求在Odoo 10里完全可以搞定,我分两种常见场景给你详细说明:
场景1:在产品分类的表单中直接展示该分类下的所有产品
这应该是你最可能需要的情况——打开某个产品分类的表单时,直接看到它下面的所有产品列表,而不是通过下拉选择。
步骤1:给产品分类模型添加One2Many字段
首先,我们需要在product.category模型中新增一个One2Many字段,关联到product.product(因为产品模型默认已经有指向分类的Many2One字段categ_id):
from odoo import models, fields class ProductCategory(models.Model): _inherit = 'product.category' product_ids = fields.One2many( comodel_name='product.product', inverse_name='categ_id', string='Products in This Category' )
步骤2:修改分类的表单视图,添加树形列表展示
接下来,我们继承默认的产品分类表单视图,把新增的product_ids字段以树形列表的形式嵌入进去:
<record id="product_category_form_inherit" model="ir.ui.view"> <field name="name">product.category.form.inherit</field> <field name="model">product.category</field> <field name="inherit_id" ref="product.product_category_form_view"/> <field name="arch" type="xml"> <!-- 把产品列表添加到描述字段后面,你可以根据需求调整位置 --> <xpath expr="//field[@name='description']" position="after"> <field name="product_ids" widget="one2many_list"> <tree string="Products"> <!-- 这里可以自定义显示的产品字段 --> <field name="name"/> <field name="default_code"/> <field name="list_price"/> <field name="qty_available"/> </tree> </field> </xpath> </field> </record>
这样配置后,打开任意产品分类的表单,就能直接看到该分类下所有产品的列表,完全替代了下拉选择的方式。
场景2:在自定义表单中选择分类后,动态展示对应产品
如果是在某个自定义的业务表单中(比如一个采购申请单),需要用户选择分类后,自动展示该分类下的产品列表,我们可以用计算字段+onchange的方式实现:
步骤1:创建自定义模型
from odoo import models, fields, api class CustomBusinessForm(models.Model): _name = 'custom.business.form' _description = 'Custom Business Form' categ_id = fields.Many2one('product.category', string='Select Product Category') # 用非存储的计算字段来动态加载产品 product_ids = fields.Many2many( comodel_name='product.product', string='Products in Category', compute='_compute_filtered_products', store=False ) @api.onchange('categ_id') def _compute_filtered_products(self): """当分类改变时,自动过滤出对应产品""" if self.categ_id: self.product_ids = self.env['product.product'].search([ ('categ_id', '=', self.categ_id.id) ]) else: self.product_ids = False
步骤2:配置自定义表单视图
<record id="custom_business_form_view" model="ir.ui.view"> <field name="name">custom.business.form.view</field> <field name="model">custom.business.form</field> <field name="arch" type="xml"> <form string="Custom Business Form"> <sheet> <group> <field name="categ_id"/> </group> <group> <!-- 用many2many_list widget展示树形列表 --> <field name="product_ids" widget="many2many_list"> <tree string="Filtered Products"> <field name="name"/> <field name="default_code"/> <field name="list_price"/> </tree> </field> </group> </sheet> </form> </field> </record>
这样用户在表单中选择产品分类后,下面会自动加载并展示该分类下的所有产品,完全不需要通过下拉选择。
注意:两种场景的核心都是用one2many_list或many2many_list widget,让字段以树形列表的形式展示,而不是默认的下拉选择框。
内容的提问来源于stack exchange,提问作者majid
相关产品推荐
相关产品推荐

