Odoo开发:如何将产品查询记录传递到另一向导的Many2many字段
可行实现方案
首先先修正你现有代码的两处问题:
- 分类查询的循环逻辑有误,每次遍历分类都会覆盖
product_res变量,且搜索条件应该用in匹配多个分类id - 目标向导
product.selection需要先定义好存储产品的Many2many字段,假设该字段名为selected_product_ids,字段定义参考:
class ProductSelection(models.TransientModel): _name = 'product.selection' selected_product_ids = fields.Many2many('product.product', string='筛选后产品')
方法1:返回向导时通过context传默认值
这是最简单的方案,在返回的act_window中添加context参数,给目标向导的Many2many字段设置默认值:
def start_search_product(self): wiz_form = self.env.ref('product_filter.get_products_form_all', False) # 修正产品查询逻辑,直接批量搜索所有选中分类下的产品 product_res = self.env['product.product'].search([('categ_id', 'in', self.category_select.ids)]) return { 'type': 'ir.actions.act_window', 'name': "Product Filtered", 'res_model': 'product.selection', 'target': 'new', 'view_id': wiz_form.id, 'view_mode': 'form', # 新增context传默认值,default_前缀后跟目标字段名,Many2many传(6,0,id列表)格式 'context': { 'default_selected_product_ids': [(6, 0, product_res.ids)] } }
说明:Odoo中Many2many字段写入的(6,0,ids)是ORM约定的操作符,代表清空现有关联后绑定指定id列表的记录
方法2:先创建目标向导记录再跳转
如果需要对目标向导做更多初始化操作,可以先创建记录再跳转至该记录的表单:
def start_search_product(self): wiz_form = self.env.ref('product_filter.get_products_form_all', False) product_res = self.env['product.product'].search([('categ_id', 'in', self.category_select.ids)]) # 先创建product.selection记录,直接赋值产品字段 selection_wiz = self.env['product.selection'].create({ 'selected_product_ids': [(6, 0, product_res.ids)] }) return { 'type': 'ir.actions.act_window', 'name': "Product Filtered", 'res_model': 'product.selection', 'res_id': selection_wiz.id, # 指定跳转的记录id 'target': 'new', 'view_id': wiz_form.id, 'view_mode': 'form', }
内容的提问来源于stack exchange,提问作者Sidharth Panda
相关产品推荐
相关产品推荐

