Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I iterate on django query set or over the variable?

I have a large dataset returned from django queryset and I want to iterate over it. Should I directly iterate over the queryset or store the results in a variable and iterate over it?

for item in Model.objects.all():
    do_something()

or

results = Model.objects.all():
for item in results:
    do_something()

As far as I know, the variables are stored in heap and its safer, where as in case of iterating over queryset, the results will be stored in main memory.

So which one is efficient in space and speed?

like image 388
Saiteja Parsi Avatar asked May 19 '17 09:05

Saiteja Parsi


People also ask

What is query set in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data. In this tutorial we will be querying data from the Members table.

How do you find the length of a query set?

If the QuerySet only exists to count the amount of rows, use count(). If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.


1 Answers

There is no difference. Python does not distinguish between data on the heap and "main memory" (or the stack); in CPython at least, all data is stored on the heap, and the stack contains references to that data. See this question.

The only consideration here is whether you need to refer to the queryset again in the same scope. If you do, store it in a variable; if not, then there is no need to.

like image 92
Daniel Roseman Avatar answered Sep 19 '22 18:09

Daniel Roseman