6

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Actually my example implied I want the same value in all, but actually this will not be the case. I think you have answered the question though, in my real case it is unavoidable, as I want to note for each item if an attempted action (sending an email) was successful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.