Django update queryset in a single line

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.

syntax

Students.objects.all().update(is_active=True)
Student.objects.filter(is_active=False).update(is_active=True)
  1. The first queryset will retrieve all the students and set them as active.
  2. The second queryset will retrieve the students who are inactive and activate them.

Example

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.

  1. Traditional approach.
  2. 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.

Conclusion

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.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *