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:
- all the work is done outside of the
transaction.atomic
transaction.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 query
More information could be found here: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#bulk-update
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…