tags:

views:

108

answers:

1

How can I NOT have the full result set from mysql copied into memory in django? I'm itterating over a BIG table which is blowing up my ram when the query copies.

It seems that mysql uses SSCursor for this purpose, and I can do all that with the mysql low level interface, but is there a Django way to do it?

+1  A: 

This will get 500 items each iteration:

count = Model.objects.count()
chunk = 500
for i in range((count/chunk)+1):
    objs = list(Model.objects.all()[i*chunk:(i+1)*chunk])

You might also want to have a look at the QuerySet method iterator().

stefanw
Is this as optimal as an unbuffered cursor over the data set? If not, how much worse?
Paul Tarjan
Afaik What this effectively does is "SELECT stuff FROM table LIMIT <(i+1)*slice> OFFSET <i*slice>." You were worried about your memory usage, this will solve it, because it just keeps a fixed number of rows in memory. The downside is that there are multiple SQL queries, but this shouldn't be too bad.
stefanw
The iterator() thingy seems to read the result line by line, so it might be the thing you're looking for.
che
Actually, the iterator() keeps the whole thing in memory as well sadly
Paul Tarjan