'Bulk save edited items with Django?
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
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |