0

I have very simple django app:

models.py:

class Product(models.Model):
        name = models.CharField(max_length=1000, default="")
        desc = models.TextField(default="")

views.py:

from django.http import HttpResponse
from models import Product

def fetch(request):
        for p in Product.objects.all()[:300000]:
                pass
        return HttpResponse("done")

I've loaded 300k sample records in MySQL database, turned debug off in settings.py and tried executed fetch view - after it completes, django still sits on 700Mb of RAM

I understand that it needs memory to fetch all these 300k objects, but why on earth it keeps them after view functions exits?

Again, I'm with DEBUG=False, tried this with django dev web server and also with uwsgi and its the same weird behavior.

P.S. Verified with Django 1.4 and 1.5.4 on both python2.6/2.7 Linux 64-bit

2 Answers 2

3

This is not really anything to do with Django. Generally, Python does not return memory to the operating system until it needs to.

See the effbot's explanation for more detail.

Sign up to request clarification or add additional context in comments.

3 Comments

But somehow if I just allocate array of strings instead of Django QuerySet it gets freed after I exit a view function. There must be something different about querysets. Following your thinking, I can suggest that using Django ORM for anything but small data sets is absolutely impractical.
I wouldn't be surprised if strings were handled differently then other (non-primitive) objects. But I haven't tested it.
Well, Exelian, you are right - creating a bunch of dummy class instances instead of model objects produces the same behavior. So its not a django, its a Python's memory management.
0

This line is the culprit

for p in Product.objects.all()[:300000]:

The slicing forces the QuerySet to evaluate, ie. hit the database, and it then returns a list() containing the slice of objects, which you then can iterate over. And Django's QuerySet cache keeps it in memory since you might want to iterate over the same "QuerySet" again.

You could optimize this by using an iterator.

It's in the docs here

1 Comment

I have no problem with returning 300k objects from DB. But it expect them to be freed when view function finishes - this is what my question is about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.