Deniz Dogan
Deniz Dogan

Reputation: 26227

Modifying an attribute for each object in a queryset

I've been using Django for over a year, but I think I've missed out on some very fundamental thing. I have a rather large queryset (1000+ objects) and I'd like to change a single attribute for each of the objects in that queryset. Is this really the way to go? I'm sure there is something simpler?

for obj in qs:
  obj.my_attr = True 
  obj.save()

Thanks

Upvotes: 4

Views: 4742

Answers (1)

Paolo Bergantino
Paolo Bergantino

Reputation: 488544

You can just do the changes in bulk, although this will not fire the Model's save() callbacks:

MyModel.objects.filter(..).update(my_attr=True)

Documentation: Updating multiple objects at once

Upvotes: 19

Related Questions