Django: change the value of a field for all objects in a queryset

PythonDjangoDjango Queryset

Python Problem Overview


I have a model MyModel with a boolean field active

Elsewhere, I am retrieving a queryset:

qs = MyModel.Objects.filter(....) 

how can I set active=False for all objects in this qs?

Python Solutions


Solution 1 - Python

You can update all the records in the queryset with

qs.update(active=False)

Please refer to the official Django documentation for more info

Solution 2 - Python

And of course you can pass many arguments to update e.g.:

qs.update(active=False, is_deleted=True, date_finished=timezone.now())

Edit: Additionally. This simple qs.update(...) won't work on sliced querysets. For example if you have:

users = User.objects.filter(is_active=True)[:10]
user.update(is_active=False)  # This will throw error

in that kind of situation, since Django 2.2, you can use bulk_update() method like:

users_to_update = list(User.objects.filter(is_active=True)[:10])
for i in range(10):
    users_to_update.is_active = False

User.objects.bulk_update(users_to_update, ["is_active"])

This will be generally done in one query not in 10 separate queries. I've faced that kind of requirements in one of my project. Hope it will be helpful.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question43TesseractsView Question on Stackoverflow
Solution 1 - PythonPynchiaView Answer on Stackoverflow
Solution 2 - PythonMichael StachuraView Answer on Stackoverflow