Caching queries in Django
Posted
by
dolma33
on Stack Overflow
See other posts from Stack Overflow
or by dolma33
Published on 2011-01-11T17:44:15Z
Indexed on
2011/01/11
20:53 UTC
Read the original article
Hit count: 191
In a django project I only need to cache a few queries, using, because of server limitations, a cache table instead of memcached.
One of those queries looks like this:
Let's say I have a Parent
object, which has a lot of Child
objects.
I need to store the result of the simple query parent.childs.all()
.
I have no problem with that, and everything works as expected with some code like
key = "%s_children" %(parent.name)
value = cache.get(key)
if value is None:
cache.set(key, parent.children.all(), CACHE_TIMEOUT)
value = cache.get(key)
But sometimes, just sometimes, the cache.set
does nothing, and, after executing cache.set
, cache.get(key)
keeps returning None
.
After some test, I've noticed that cache.set
is not working when parent.children.all().count()
has higher values.
That means that if I'm storing inside of key
(for example) 600 children objects, it works fine,
but it wont work with 1200 children.
So my question is: is there a limit to the data that a key could store? How can I override it?
Second question: which way is "better", the above code, or the following one?
key = "%s_children" %(parent.name)
value = cache.get(key)
if value is None:
value = parent.children.all()
cache.set(key, value, CACHE_TIMEOUT)
The second version won't cause errors if cache.set
doesn't work, so it could be a workaround to my issue, but obviously not a solution.
In general, let's forget about my issue, which version would you consider "better"?
© Stack Overflow or respective owner