Update a field for all objects in a Django QuerySet

In some cases you may want to update a field, or multiple fields, for a collection of Django models in a QuerySet object. For those use-cases you may use the .update() method on the QuerySet object.

User.objects.filter(last_login=None).update(is_active=False)

The .update() method allows you to update fields for all the objects in your QuerySet. This is illustrated in the following example, which uses a .filter() method to select the objects which should be updated. However, if you want to apply a change to all objects you can use .all() instead.

When you run this line in the Django shell you might be surprised by the return value of the statement. The .update() method returns the number of rows matched by the query, which is not necessarily equal to the amount of rows updated.

There is a gotcha when updating objects like this though. This method directly runs an SQL statement without calling the save() method on your model and therefore not call any pre_save or post_save signals.

Of course Django provides excellent docs on this particular feature.

See Also

6 Non-Programming Books for Programmers