Django: Caching Querysets

April 28th, 2008  |  Published in Django, Web Development  |  1 Comment

I have just recently started working with Django again, its been a while since I last used it. One thing I was trying to do was cache querysets, which doesn’t work. Before the recent merge of the queryset refactor branch into trunk, caching querysets appeared to work, in reality it didn’t. Now with the merge of queryset refactor branch, it fails with a Python error. Malcom (the author of the queryset refactor branch) wrote up the reason for this on the django mailing list in this thread.

The solution? Force the queryset to a list. For example:

1
2
3
queryset = Widget.objects.all()
wlist = list(queryset)
cache.set("allwidgets", wlist, 3600)

This does mean that you can’t use the cached list as a queryset, so you’ll have to cache it after all the filtering, ordering, etc. has been done.

Responses

  1. ali asaria says:

    May 26th, 2008 at 1:05 pm (#)

    I had the same problem with json-dumping a queryset. Django does such a good job of making queryset’s accessible, that I forget that they aren’t a list.

Leave a Response

Subscribe via RSS

If you like the content of this website and are looking for a way to be notified of new content, look no further. Just click the orange icon to your right and subscribe using your favorite feed reader.