goh
goh

Reputation: 29511

Django: how can I update more than one record at once?

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

Answers (3)

Ebram Shehata
Ebram Shehata

Reputation: 621

You can use QuerySet's bulk_update

Example:

YourModel.objects.bulk_update(queryset_or_list_of_objs, ["field1", "field2", ...])

Upvotes: 0

Josh Smeaton
Josh Smeaton

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

cy lee
cy lee

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

Related Questions