John Mc
John Mc

Reputation: 411

Why does .save() still take up time when using transaction.atomic()?

In Django, I read that transaction.atomic() should leave all the queries to be executed until the end of the code segment in a single transaction. However, it doesn't seem to be working as expected:

import time
from django.db import transaction
my_objs=Obj.objects.all()[:100]
count=avg1=0
with transaction.atomic():
    for obj in my_objs:
        start = time.time()
        obj.save()
        end = time.time()
        avg1+= end - start
        count+= 1
print("total:",avg1,"average:",avg1/count)

Why when wrapping the .save() method around a start/end time to check how long it takes, it is not instantaneous?

The result of the code above was:

total: 3.5636022090911865 average: 0.035636022090911865

When logging the SQL queries with the debugger, it also displays an UPDATE statement for each time .save() is called.

Any ideas why its not working as expected?

PS. I am using Postgres.

Upvotes: 0

Views: 706

Answers (1)

sytech
sytech

Reputation: 40941

There is probably just a misunderstanding here about what transaction.atomic actually does. It doesn't necessarily wait to execute all the queries -- the ORM is still talking to the database as you execute your code in an atomic block. It simply waits to commit (SQL COMMIT;) changes until the [successful] end of the block. In the case there is an exception before the end of the transaction block, all the modifications in the transaction are not committed and are rolled back.

Upvotes: 4

Related Questions