There are two ways to update multiple model instances in efficient manner.
- Using
.bulk_update
method
bulk_update(objs, fields, batch_size=None)
objects_list = [
Post.object.create(title="Tutorial 1"),
Post.object.create(title="Tutorial 2"),
]
objects_list[0].title = "Super Tutorial 1"
objects_list[1].title = "Mega Tutorial 2"
Post.objects.bulk_update(objects_list, ['headline'])
Details and Caveats:
- It will be executed in a single query
.save()
method will not be called- pre and post save signals will not be sent
- Updating using
.update()
method on the queryset:
If you need to update objects matching the certain criteria you may do so by calling .update()
method on the QuerySet.
In this example we may want to unpublish all posts that have "Tutorial" in the title.
Post.objects.filter(title__icontains="tutorial").update(is_published=False)
Details and Caveats:
- It will be executed in a single query, thus done fast
.save()
method and pre & post save signals will not be sent.