Reputation: 2591
I cant seem to find the documentation for this, but I want to update the record within a loop of a QuerySet example:
data = Site.objects.all()
for i in data:
... do stuff
i.update(field="value")
I know I could do it by:
data = Site.objects.all()
for i in data:
... do stuff
Site.objects.filter(pk=i.pk).update(field="value")
but this seems inefficient as I already have the record, so shouldn't need to query for it again?
Thanks
Upvotes: 2
Views: 4502
Reputation: 15916
Just use save
:
data = Site.objects.all()
for i in data:
# ... do stuff
# i.update(field="value")
i.field = value
i.save()
n.b., updating objects in a loop is woefully expensive, especially for a large number of objects. And, no matter what, the save will cost you an additional query.
Upvotes: 11