问题
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!
回答1:
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})]
回答2:
.create
method creates a record into the database, so it's expected to do so,
if I understood you, I think you should use something like TransientModel
or AbstractModel
?!
An Abstract model is created by a class based on models.AbstractModel instead of
the usual models.Model. It has all the attributes and capabilities of regular models; the
difference is that the ORM will not create an actual representation for it in the database. So,
it can have no data stored in it. It serves only as a template for a reusable feature that is to be
added to regular models.
来源:https://stackoverflow.com/questions/56092261/how-to-create-a-record-without-saving-it-in-database