2

I am editing a large number of model instances in django and I would like to save all these changes at once.

The instances are already created so I am not looking for bulk_create. The changes are also different for each instance, so I can't use QuerySet.update(...) to apply the same change to all of them.

I would like to replace this:

for item in items_to_modify:
    item.some_field = process_new_data()
    item.save()

by something like:

for item in items_to_modify:
    item.some_field = process_new_data()

items_to_modify.save_all_at_once()

I am using django 3.1

Ryan Pergent
  • 4,432
  • 3
  • 36
  • 78
  • 1
    You want [bulk_update](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#bulk-update)? – drec4s Apr 13 '21 at 13:07
  • @alfonso Oh, I absolutely missed that! I didn't realize there was something else than `QuerySet.update`. I think that might be what I need. – Ryan Pergent Apr 13 '21 at 13:09
  • 1
    Dajngo 2.2 supports `bulk_update` ref: https://stackoverflow.com/a/12661327/6027876 – Aarif Apr 13 '21 at 13:09

1 Answers1

2
user_ids_dict = {
  1: 100,
  2: 150,
  3: 500
}

from django.db import transaction

with transaction.atomic():
  for key, value in user_ids_dict:
    User.objects.filter(id=key).update(score=value)

sometimes you need smth like this