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.
.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
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.