13

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.

onurmatik
  • 5,105
  • 7
  • 42
  • 67

1 Answers1

13

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.

Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83
  • thanks for the reply. i added link to an example code to the question. please let me know if further clarification would help. – onurmatik Nov 18 '10 at 16:32
  • It could be some transactional issue like this one: http://stackoverflow.com/questions/2235318/how-do-i-deal-with-this-race-condition-in-django/2235624#2235624 (note that it's MySQL-specific), but looking at your code I see that the two versions are not equivalent - the working version `get()s` by `slug` and `create()s` with `name`, whereas the other version `create()s` with `name` **and** `slug`. So maybe this assymetry is behind the problem. – Tomasz Zieliński Nov 19 '10 at 01:08