Creating block objects by assigning values to many2many field

150 views Asked by At

I'm trying to create a feature to create massive instances through a wizard, assigning values ​​to some many2many fields, but at the time of the test I get an error:

Singleton expected: model3(167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 188, 187, 188, 190, 191, 193, 194, 195, 1978, 1978, 2007, 1920, 202, 203, 204, 20, 20, 20, 20, 20, 20, 20, 20, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246)

I leave the code in case you can help me.

class Modelo1Model(models.Model):
    _name = 'modelo1'

    mod1_modelo3_ids = fields.Many2many('modelo3')

class Modelo2Model(models.Model):
    _name = 'modelo2'

    mod2_modelo3_ids = fields.Many2many('modelo3')

class Modelo3Model(models.Model):
    _name = 'modelo3'

    #...

class Modelo1Wizard(models.TransientModel):
    _name = 'modelo1.wizard'

    def _default_i(self):
        return self.env['modelo1'].browse(self._context.get('active_ids'))

    modelo1_ids = fields.Many2many(
        'modelo1',
        default = _default_i)

    @api.multi
    def create_modelo2(self):
        for i in self.modelo1_ids:
            registros_many2many = i.mod2_modelo3_ids.ids
            i.ensure_one()
            modelo2_obj = self.env['modelo2']
            modelo2_vals = {
                'mod2_modelo3_ids': registros_many2many
                 }
            modelo2_create_id = modelo2_obj.create(modelo2_vals)
2

There are 2 answers

1
George Daramouskas On

@api.multi

When you decorate your method with this decorator you imply that self will be a recordset. In order to properly write to your records you have to iterate. Example:

@api.multi
    def create_modelo2(self):
        for record in self:
            for i in record.modelo1_ids:
0
Axj46 On

Solved by following this, here show how to work with fields x2many