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

时间:2017-12-05 11:18:49

标签: openerp odoo-10

我需要将many2many字段内容复制到另一个类'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" />

但它返回nom_risque,而rubrique_ids只返回最后一个。

1 个答案:

答案 0 :(得分:1)

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

@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
    }