Is it efficient to obtain a queryset, and iterate over it in a conventional loop, saving the changes to each item using save()
? e.g.
for mod in mymodel.objects.all():
# modify
mod.name = 'new name or whatever'
# Save
mod.save()
If not, is there a better way? The docs state that calling save()
hits the database which is why I ask. I'm a relative newbie to Django (and Python). In the real case, I will not be iterating over the entire database.
Not efficient, but sometimes you have to. However you can use .update()
especially if it's the same value you want to put in, or if there's an easy way to predict them
so for your example: MyModel.objects.all().update(name='new name')
, this won't loop over the entire table, it pretty much translates to UPDATE my_model SET name = 'new name'
You can do a multiple update following a filter too, ref: https://docs.djangoproject.com/en/1.7/topics/db/queries/#updating-multiple-objects-at-once
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With