将 Many2many 字段值复制到另一个 Many2many 字段

Copying Many2many field values to another Many2many field

我需要将 many2many 字段内容复制到另一个 class' many2many 字段。

 @api.multi
 def tester(self):
    context = self._context.copy()
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }

我的XML代码:

  <button name="tester" string="Evaluer" type="object" class="oe_highlight" />

但它 returns nom_risque 和 rubrique_ids 只有最后一个。

您好,请尝试以下内容,也请尝试理解我的评论:-)

@api.multi
# even if it's trying out something, give it an understandable name
def tester(self):
    # seems to be a singleton call, so restrict it with self.ensure_one()
    # no need to copy the context here, just pass it in the end
    context = self._context.copy()
    # odoo's recordsets has some cool functions, e.g. mapped()
    # but that's only usefull on other scenarios
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    # you will call this new record later so don't forget to 'save' it
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        # that's just plain wrong, read the __doc__ on models.BaseModel.write()
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        # here is the mistake: take the id of your created record above
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }

现在是希望工作的示例:

@api.multi
def create_test_record(self):
    self.ensure_one()
    test = self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [(6, 0, self.risque.rubrique_ids.ids)]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': test.id,
        'flags': {'initial_mode': 'edit'},
        'context': self.env.context
    }