Django - queryset caching request-independent?

181 Views Asked by At

I need to cache a mid-sized queryset (about 500 rows). I had a look on some solutions, django-cache-machine being the most promising.

Since the queryset is pretty much static (it's a table of cities that's been populated in advance and gets updated only by me and anyway, almost never), I just need to serve the same queryset at every request for filtering.

In my search, one detail was really not clear to me: is the cache a sort of singleton object, which is available to every request? By which I mean, if two different users access the same page, and the queryset is evaluated for the first user, does the second one get the cached queryset?

1

There are 1 best solutions below

2
On BEST ANSWER

I could not figure out, what problem you are exactly facing. What you are saying is the classical use case for caching. Memcache and redis are two most popular options. You just needs to write some method or function which first tries to load the result from cache, if it not there , the it queries the database. E.g:-

from django.core.cache import cache

def cache_user(userid):
       key = "user_{0}".format(userid)
       value = cache.get(key)
       if value is None:
             # fetch value from db
             cache.set(value)

       return value

Although for simplicity, I have written this as function, ideally this should be a manager method of the concerned model.