Skip to Content
Menu
This question has been flagged
1 Reply
23210 Views

Hello my friends,

I would like to create a new records  of class  "B" from function. This record have relation Many2one with another class "A".

The class "A" have One2many relation with the class "B". My creation function is as follows : 


self.env['affichage2.sensor_stock'].create({
'sensor_type': sensorconfig,
'serial_capture': self.internal_Serial,
'pack_id': self.public_id,

})

The 'pack_id'  of the class "B" is declared as follows : 

pack_id = fields.Many2one('affichage2.pack_stock', string='Pack de capture')

The 'public_id' of class "A" is declared as follows : 

public_serial = fields.Char(string="Public_Serial", required=True)

The class "A" is named by the "public_serial" field as follows :  _rec_name = 'public_serial'

Avatar
Discard
Best Answer

Hi Zakaria

I think you have a mistake in the fields you shows because you left out the public_id definition, but assuming that it's:

sensor_ids = fields.One2many('affichage2.sensor_stock', 'pack_id', string='*********')

You have 2 ways to create records for the model affichage2.sensor_stock:

1- Directly create it doing it like you shows in your code by set the Many2one field pack_id

self.env['affichage2.sensor_stock'].create({
'sensor_type': sensorconfig,
'serial_capture': self.internal_Serial,
'pack_id': self.public_id.id,
})

2- By making a write for the public_id field in the write format for One2many relationships:

self.public_id.write({
    'sensor_ids': [
        (0,0, {'sensor_type': sensorconfig, 'serial_capture': self.internal_Serial}),
        (0,0, {'sensor_type': 'value2', 'serial_capture': 'capture2'})
    ]
})

I add another line for value2 to show you how to create multiple records using this form, and those will be associated to self.public_id without the need to specify the pack_id value


The first way is more simple and direct than the second one but it's up to you...


Avatar
Discard
Author

Thank you Axel, i will try that

Author

Hi bro , i get this erreur:

The operation cannot be completed, probably due to the following:

- deletion: you may be trying to delete a record while other records still reference it

- creation/update: a mandatory field is not correctly set

[object with reference: affichage2_pack_stock - affichage2.pack.stock]

could you update your code to check how you do it?

Author

Hi Axel, i have resolved that, i just made that :

res = super(Pack_Stock, self).create(vals)

self.env['affichage2.sensor_stock'].create({

.........................

'pack_id': res.id,

})