Search code examples
odoorecordsetodoo-12

How to create a record without saving it in database


I'm using the Inventory addon of Odoo 12 (but my problem could happen with any module).

In this addon, a StockMove model has a move_line_ids field.
In the Detailed Operations dialog, we can see a tree view of all the move lines of the selected move.

If we click the Add a line button, and set the fields, the values are stored in memory, but not in database unless we click the Confirm button.

I would like to copy this behaviour in a @api.onchange() method of my custom StockMove model, but I don't find how to proceed.
If I use the self.move_line_ids.create() method to create my new record, the move line will be stored in the database even if I don't click the Confirm button.

Is there someone who managed to do that?

Thank you in advance!
And sorry if it is a duplicate question, but I did not found the answer to my question yet ><


The jzeta answer is working but breaks other Move fields like reserved_availability (always 0) or quantity_done (always 1).


I am keeping jzeta as validated as the comments show the solution I was looking for.

Thank you a lot guys for your help!


Solution

  • I believe you can achieve it by directly assigning the value to move_line_ids. Of course, given the field is a One2many, you need to use the special list of triplets to achieve this. In your case, you need a [(0, _, values)] for you want to create a new record (where values is the dictionary that holds each new record's field values). In the example below I only create one record attached to a given stock.move instance and I merely pass the move_id value in the dictionary. You should complete the code with the appropriate values for the new move line, but note that you should always tell the new record which stock move it is been linked to.

    @api.onchange('your_field_name')
    def _onchange_field(self):
        self.move_line_ids = [(0, False, {'move_id': self.id})]