如何在create()函数中获取动态many2many字段的值

问题描述 投票:1回答:1

我想从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
python odoo odoo-11 odoo-12
1个回答
1
投票

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 and Many2many use a special "commands"

:我假设如果您不需要首先检查字段是否不为空,则该字段将不为空。

© www.soinside.com 2019 - 2024. All rights reserved.