[Fixed]-Django queryset and generator

24👍

The former will be slower, since it will create a list containing all the models and then yield them one at a time, whereas the latter will just use the list directly. If you want a generator then you should use QuerySet.iterator() instead.

6👍

No. Other than the fact that it’s more verbose, redundant, and not particularly useful (in the context of the generator you provided).

When you do Item.objects.all() in a for, they’re iterated using iterator with query caching (source). If you don’t want the results to be cached, use iterator() like Ignacio recommends.

👤Jeff

Leave a comment