Just out of the blue I wonder if the following way of iterating through a result set using generator will cause any positive or negative impact against normal iteration?
eg.
def all_items_generator():
for item in Item.objects.all():
yield item
for item in all_items_generator():
do_stuff_with_item(item)
against:
for item in Item.objects.all():
do_stuff_with_item(item)
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.
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.
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