Mansur Fattakhov
Mansur Fattakhov

Reputation: 387

django transaction

I have a code, something like this

def many_objects_saving(list_of_objects):
    for some_object in list_of_objects:
        # do smth with an object
        some_object.save()

As I know, django is going to hit the database everytime it reaches save() in code. So here are two questions:

  1. If I will use this function in another one and make it wrapped with transaction.commit_on_success or transaction.commit_manually decorators, will django do all the saves in just one transaction and hit the database less (inside one function)?

example:

def resave_objects(model, condition):
    list_of_objects = model.objects.filter(**condition)
    many_objects_save(list_of_objects)

@transaction.commit_on_success
def many_objects_save(list_of_objects):
    for some_object in list_of_objects:
        # do smth with an object
        some_object.save()

2. And if so, will it be better for large querysets? Thank you guys!

Upvotes: 1

Views: 552

Answers (1)

madjar
madjar

Reputation: 12951

All the saves will be wrapper into a single transaction, but not in a single query. Using transactions won't change the number queries you do.

Transaction are not there for performance, but for data integrity. If you wrap your view in a transaction and fail at some point (maybe some data in the middle is wrong and you can't recover from the error), it is possible to abort the transaction, and none of the previous queries in the transaction will have any effect on the database. This way, you can make sure that you don't have half-baked datas from failed requests.

If you problem is the performance of a lot of save, you could use a bulk delete/create approach. Here is an example of it in a project of mine. The idea is that you delete all the objects in one query, then recreate them all the new values in one single queries. It won't work in all situations, but it may do the trick.

Upvotes: 3

Related Questions