Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 360
43Tesseracts Avatar asked Jan 16 '16 22:01

43Tesseracts


People also ask

How do I update QuerySet values in Django?

If you then use object[0] you make a query to the database to fetch the first element and deserialize it into a News_Channel object. Then you set the total_star of that object, but you never save that object. You only call . update() on the entire queryset, resulting in another independent query.

How do I update a field in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.

Why are QuerySets considered lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.


2 Answers

You can update all the records in the queryset with

qs.update(active=False) 

Please refer to the official Django documentation for more info

like image 59
Pynchia Avatar answered Oct 06 '22 03:10

Pynchia


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.

like image 41
Michael Stachura Avatar answered Oct 06 '22 05:10

Michael Stachura