I've read that Django > 1.9 introduces transaction.on_commit
in order to avoid race conditions. I know that Django sets database autocommit to true by default, so each query becomes a transaction at db level.
However, take this example,
from django.db import transaction
def some_view(request):
obj = SomeModel.objects.create(field=value)
transaction.on_commit(lambda: some_async_task(obj.pk))
Why should I wrap some_async_task(obj.pk)
inside transaction.on_commit
? I'm not sure how transactions work behind the scenes. All this time I've been thinking that as autocommit is enabled, create
or save
method should be a transaction itself, and then, in the next statement that object should exist in database.