AlexW
AlexW

Reputation: 2591

Django - loop through through records and update the record inside the loop?

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

Answers (1)

2ps
2ps

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

Related Questions