Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Difference between save() and create() from transaction perspective

The create() method in Django creates a model instance then calls save(), which is said to trigger commit. So there should not be any difference in triggering transaction's commit.

But in reality, executing a method that creates a bunch of model instances using create() on Postgresql I am getting transaction aborted, commands ignored until end of transaction exception. The method runs fine with non-transactional db backends. Also, when I replace the create()s with:

m = Model(attr1=..., attr2=...)
m.save()

it runs on Postgresql fine too.

Is there a difference between using save() and create() in the sense of transactions?

edit: create() also sets self._for_write = True before calling save(), but I couldn't trace it to see if it has any effect on transaction behavior.

edit: example code can be found here.

like image 445
onurmatik Avatar asked Nov 17 '10 16:11

onurmatik


People also ask

What does save () do in Django?

The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.

What is the difference between save and update in Django?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database. update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.

Do you need to call save after create Django?

create() will automatically save, so even if you fix your error - you will still have to make sure the arguments to create fulfill the database requirements to save a record.

Does objects create save?

objects. create() and u. save() both perform the same save() function.


1 Answers

As you've probably seen, create() is just a wrapper for save():

The _for_write part is most probably meant only for database selection, so I wouldn't pay too much attention to it.

And regarding that "transaction aborted" error, without seeing your code it's hard to say what the problem is. Maybe you e.g. violated UNIQUE constraint with create(), which causes PostgreSQL to demand transaction rollback, and then you tried save() with different data - it's hard to tell without the exact code.

like image 93
Tomasz Zieliński Avatar answered Oct 23 '22 17:10

Tomasz Zieliński