2

I'm hoping this will be a really simple question.

I just wanted some advise on the bulk updating of records.

An example bulk update may go something like this:

for user in User.objects.all().iterator():
    user.is_active = False
    user.save()

Is there a more efficient way to do this on the database level using the Django ORM?

Would the following be more efficient:

User.objects.all().update(is_active=False)?
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76

3 Answers3

2

Yes, using update would be more efficient. That will do a single database call, instead of one per object.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

Yes. You can use User.objects.all().update(is_active=False).

This will result in a single query that looks like:

UPDATE `auth_user`
SET `is_active` = 0

It will thus reduce the number of roundtrips to the database to one.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

It will work, but be aware that the update command will be converted directly to a SQL command, without running anything you customized on save and without triggering the save signals. If in your case there is no problem and you are more worried with the performance, go for it.

From django docs:

Be aware that the update() method is converted directly to an SQL statement. It is a bulk operation for direct updates. It doesn’t run any save() methods on your models, or emit the pre_save or post_save signals (which are a consequence of calling save()), or honor the auto_now field option. If you want to save every item in a QuerySet and make sure that the save() method is called on each instance, you don’t need any special function to handle that.

https://docs.djangoproject.com/en/2.2/topics/db/queries/#updating-multiple-objects-at-once

Marcelo
  • 2,245
  • 4
  • 20
  • 24
  • I have decided to accept this answer out of the three so far (@WillemVanOnsem's and @DanielRoseman's) because it adds in the caveat regarding `post_save` triggers using the `.save()` method. Although this was not necessary for a bulk uplaod - it still helps to understand bulk queries like this. – Micheal J. Roberts Oct 02 '19 at 14:56