Skip to Content
Menu
This question has been flagged
4 Replies
37600 Views

Hello,


Could anyone explain how ORM API works with write() and update().  

AFAIK, CRUD represents create, read, update, delete which corresponds to create(), read(), update(), unlink() in ORM.

However, the explanation on odoo 13.0 documentation (\https://www.odoo.com/documentation/13.0/reference/orm.html)

write() seems to be the one to update a existing record.  

update() can do the same, and even on psedo-records that are not created yet.  

If that is the case, what are the scenarios to use write() over update()?

Avatar
Discard

Hi Guys
Please can have a example of using write() and update() ?
odoo 13

Best Answer

Hi,

Write() Updates all records in the current set with the provided values, but write() is one of the CRUD methods that do not work for records set which are not present in the database. An onchange method returns pseudo-records which do not exist in the database yet. So set record's field using update() method as calling write() method gives an undefined behavior.

Regards

Avatar
Discard
Author

If I understand you correctly.

1. CRUD, is write(), not update(), odoo ORM naming the way it is.

2. write() can update multiple records and its corresponding fields at the same time.

3. update() is designed to work with pseudo-records.

The only benefit of write() is the ability to update multiple records. Otherwise use update() in custom function?

I make this conclusion because update() can update existed records as well. I've not tried update() multiple yet though.

When setting multiple fields at the same time use write() so that if it takes a number of field values the function writes them to all the records in its recordset. self.write({'name':'Name', 'age': age})

So gives you single update statement in the database.

But update() only works on singletons and performs a database write for each written field.So at a time it updates only single record.It Iterates through the fields and sets each one separately giving you multiple update statements in the database.

for order in self:

amount_untaxed = amount_tax = 0.0

for line in order.order_line:

amount_untaxed += line.price_subtotal

amount_tax += line.price_tax

order.update({

'amount_untaxed': amount_untaxed,

'amount_tax': amount_tax,

'amount_total': amount_untaxed + amount_tax,

})

and it can be used within onchange functions as they return pseudo records.ie.update function can work on records not present in database yet.

Author

Thank you very much for the clears up.

I was doing it wrong by abusing for-loop with update().

Best Answer

Hello
in write method , all the record has been updated of model and in update method, only particular filed of record you can update. This is the main difference between write and update method.

Avatar
Discard
Author

thank you for the explanation.

Related Posts Replies Views Activity
2
Nov 19
2421
3
Apr 17
16327
1
Feb 16
2980
0
Sep 24
3
0
Sep 24
351