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.
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.
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.
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.
objects. create() and u. save() both perform the same save() function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With