r_zelazny
r_zelazny

Reputation: 557

confusion about transaction.atomic() in Django

I have a view in which I do a series of model saves like so:

with transaction.atomic():
    modelA.save()
    modelB.save() 
    ...

I want all the saves to be done at once, but when I check the database after executing modelA.save() and before executing modelB.save() I see that the table modelA writes to has been changed, that is the write to modelA has been committed to the db. I thought all the writes in a transaction.atomic() block would be committed together at the end. What am I missing? I'm using django 1.10 and Oracle 12g. Thanks

Upvotes: 0

Views: 880

Answers (2)

Alasdair
Alasdair

Reputation: 308839

If you are using multiple databases, you should specify which database to use with using:

with transaction.atomic(using='my_db'):
    modelA.save()
    modelB.save() 

Upvotes: 1

r_zelazny
r_zelazny

Reputation: 557

I found a solution:

transaction.set_autocommit(False, using='my_db')
modelA.save()
modelB.save()
transaction.commit(using='my_db')
transaction.set_autocommit(True, using='my_db')

My issue was that a constraint on the db table in question meant the saves had to be done as one transaction. For some reason transaction.atomic() didn't work...

Upvotes: 0

Related Questions