Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Is it efficient to save queryset items in loop?

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.

like image 740
crobar Avatar asked Sep 18 '14 07:09

crobar


1 Answers

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

like image 166
bakkal Avatar answered Sep 26 '22 03:09

bakkal