I have recursive function and obj.save() is inside it. how to prevent the query from db at every iteration? is django transaction.atomic do that.
I have recursive function and obj.save() is inside it. how to prevent the query from db at every iteration? is django transaction.atomic do that.
If you're using django >= 2.2 (which you should be using.. since ALL other versions of django are 100% out of support as of me writing this Jan 5, 2020) you can do this:
objs = []
for obj in Entry.objects.filter(...):
if not obj.condition:
continue
obj.headline = 'something!!!'
obj.author = 'John Smith'
objs.append(obj)
with transaction.atomic():
Entry.objects.bulk_update(objs, ['headline', 'author'])
Couple of things to note:
transaction.atomictransaction.atomic means that if anything fails inside that block, it will rollback the WHOLE work (transaction) and not keep a piece of it around. Example: you have 2 authors to save, first one saves successfully, second one does not. Because is inside the transaction atomic, it means both of them are NOT committed. It has nothing to do with doing it all in one queryMore information could be found here: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#bulk-update