[Fixed]-Should I iterate on django query set or over the variable?

19đź‘Ť

âś…

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.

12đź‘Ť

If your dataset is huge you could use iterator to reduce memory load and improve performance, e.g.

results = Model.objects.all()

for item in results.iterator():
    do_something()

You should only do this if it’s really necessary, as it disables queryset caching. Re-using the queryset after this will result in poorer performance.

👤Matt

Leave a comment