I recently came across a problem, where I had to set or alter a boolean field from True to False for all the objects of a queryset. I did not want to use a for loop to iterate over them, change the value from False to True, and save it. I looked over a solution for this and came across the update() method.
Django queryset update method
The update method can be applied to a queryset only and not to individual methods. The following is a simple syntax for the update() method of the Django queryset.
- The first queryset will retrieve all the students and set them as active.
- The second queryset will retrieve the students who are inactive and activate them.
Consider a django students model which has two fields name and is_active.
Let us say is_active is a flag that tells that a student is active or inactive. I want to query all the students who are inactive(is_active=False) and activate them (is_active=True).
This can be done by the following two ways.
- Traditional approach.
- Using update() method.
1. Traditional approach
In the traditional approach, the queryset is iterated over, the flag is set to true and each individual objects are saved one by one.
The following code snippet gives an example of this method.
2. Update method
Using the update() method this can be achieved using a single line like this.
That is it. All the student objects which are inactive are set as active using a single line with the help of an update method.
It is better to use the update method to update a queryset, which is a more pythonic way than using for loops to update them.