Hello,
I am new to Odoo and I struggle with the new Odoo API. I am trying to create new records on a Many2One field in an @api.onchange method. It is a custom module so I will simplify by providing a made up example.
Say that I am building a new Order that has Lines. The lines are defined via a Many2One field called 'line':
class Order(models.Model):
name="mymodule.order"
line = fields.One2many('mymodule.line',
inverse_name="order_id",
string="Lines")
partner_id = fields.....
.....
I want to generate new lines as soon as the user selects or changes the partner_id of the order. To do so, I have implemented an @api.onchance method that looks somewhat like this:
@api.onchange('partner_id')
def onchange_equipment_type_id(self):
""" Updates the order lines"""
if self.line:
self.line.unlink()
for val in self.bogus_values: #some bogus list that supposedly tells me how many lines I need to create
self.line.create({'name':val.name, 'order_id':self.id, ....})
The above approach does not work. First of all, as far as I understand CREATE will actually create records to the DB. I do not want that. I simply want to add some order lines as if I clicked few times on 'Add an item' in a table. The actual creation of the lines shall happen when the user clicks the Save button on the order. So what method shall I use? How can I 'add' records to the line field without writing to the DB at this point?
The second problem that I face is that self.id is NewId. Now as per my understanding this is normal for New records. But I actually get self.id as NewID even for entries that have been saved and I open them in edit mode. Anyways, for the case when the order has not been saved yet, I still need to add lines. So my major issue is how to add lines to my Many2One field as part of my onchange method without triggering a DB write.
Let me reiterate again - I want to create a Many2One not as part of the 'parent' object create method. I want to do this as an onchange event. I want to generate the lines as soon as I change the partner. Imagine that for each partner there is a predefined set of lines, for example based on favorite products. So as soon as the one changes the partner id, a new list of favorite products will be retrieved (for the selected partner), the existing order lines must be deleted and new lines (for the new product set) shall be generated. All this shall happen prior to the user hitting the Save button on the order object. Actually the user can change partners several times priori to saving the order.
I hope that my question makes some sense.
Thank you in advance for your help.