Reputation: 29511
How can I update multiple records in a queryset efficiently?
Do I just loop over the queryset, edit , and call save()
for each one of them? Is it equivalent to psycopg2's executemany
?
Upvotes: 1
Views: 7521
Reputation: 621
You can use QuerySet's bulk_update
Example:
YourModel.objects.bulk_update(queryset_or_list_of_objs, ["field1", "field2", ...])
Upvotes: 0
Reputation: 48720
If you have to update each record with a different value, then of couse you have to iterate over each record. If you wish to do update them all with the same value, then just use the update method of the queryset.
Upvotes: 6
Reputation: 41
You can use the queryset update method. Here's the documentation:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#update
If you look at the code, it does loop over the items. In fact this is what Django admin uses when doing "bulk" actions on items.
Upvotes: 3