How to 'bulk update' with Django?

Thomas Schwärzl picture Thomas Schwärzl · Sep 30, 2012 · Viewed 139.6k times · Source

I'd like to update a table with Django - something like this in raw SQL:

update tbl_name set name = 'foo' where name = 'bar'

My first result is something like this - but that's nasty, isn't it?

list = ModelClass.objects.filter(name = 'bar')
for obj in list:
    obj.name = 'foo'
    obj.save()

Is there a more elegant way?

Answer

jb. picture jb. · Sep 30, 2012

Update:

Django 2.2 version now has a bulk_update.

Old answer:

Refer to the following django documentation section

Updating multiple objects at once

In short you should be able to use:

ModelClass.objects.filter(name='bar').update(name="foo")

You can also use F objects to do things like incrementing rows:

from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)

See the documentation.

However, note that:

  • This won't use ModelClass.save method (so if you have some logic inside it won't be triggered).
  • No django signals will be emitted.
  • You can't perform an .update() on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the .filter() and .exclude() methods.