Django Query Set and Generator

Just in the distance. I wonder if the following iteration method through a result set using a generator can cause any positive or negative impact on a 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) 
+6
source share
2 answers

The first will be slower, as it will create a list containing all the models and then give them one at a time, while the latter will simply use the list directly. If you want a generator, you must use QuerySet.iterator() .

+13
source

Not. Besides the fact that it is more detailed, redundant and not particularly useful (in the context of the provided generator).

When you execute Item.objects.all() in for , they are repeated using iterator with query caching ( source ). If you do not want the results to be cached, use iterator() , as Ignacio recommends.

+4
source

Source: https://habr.com/ru/post/924692/


All Articles