Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

How to make obj.save() without reversing object values in the db in django

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...