首页 > 解决方案 > 如何在 create() 函数中获取动态 many2many 字段的值

问题描述

我想从 create() 函数中动态填充的 many2many 字段中获取值,但是我得到了这个结果 [[6, False, [98]]], 98 实际上是预期的结果,尽管这是我下面的代码

class CustomTransRequest(models.Model):
    _name = 'custom.trans.request'
    _description = 'Transfer Request'

    branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
    branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
    line_id = fields.Many2one('custom.branch.line', string="Products", required=True)
    product_id = fields.Many2many('custom.product', required=False, )
    qty = fields.Integer(string="Qty", required=True)

    @api.onchange('line_id')
    def onchange_line(self):
        if self.line_id:
            for rec in self:
                selected_products = rec.env['custom.branch.line'].search(
                    [('id', '=', rec.line_id.id)]).mapped('product_id')
                self.product_id = [(6, 0, selected_products.ids)]

    @api.model
    def create(self, vals):
        print("Create Function ")
        print("SELECT id FROM custom_branch_line WHERE (branch_id = %s) AND (product_id = %s)" % (
            vals.get('branch_to_id'), vals['product_id']))
        result = super(CustomTransRequest, self).create(vals)
        return result

标签: pythonodooodoo-11odoo-12

解决方案


这就是 Odoo 处理 X2many 字段的方式,按照惯例,大多数时候在 create 方法中它们被称为命令(或命令列表),将为您的 m2m 字段传递的命令将是:

 # only one command 6 which tell Odoo replace all record with the selected ids
 [(6, 0, [list_of_selected_record_ids)]

因此,为了检索它们,只需执行以下操作:vals['product_id'][0][2]

不,我不知道您是只是想显示选择查询还是要使用,如果您只是打印它:

  # replace vals['product_id'] with 
  '({})'.format(','.join(vals['product_id'][0][2]))

如果要执行它,请使用查询参数:

self.cr.execute("SELECT id FROM custom_branch_line WHERE (branch_id = %s) AND (product_id = %s)", (vals['branch_to_id'], vals['product_id'][0][2]))

有关 X2many 命令的更多信息,请查看:

One2many 和 Many2many 使用特殊的“命令”

注意:我假设此字段不会为空,否则您需要先检查字段是否为空。


推荐阅读