Get list of Cache Keys in Django
Solution 1
You can use http://www.darkcoding.net/software/memcached-list-all-keys/ as explained in How do I check the content of a Django cache with Python memcached?
Solution 2
For RedisCache you can get all available keys with.
from django.core.cache import cache
cache.keys('*')
Solution 3
As mentioned there is no way to get a list of all cache keys within django. If you're using an external cache (e.g. memcached, or database caching) you can inspect the external cache directly.
But if you want to know how to convert a django key to the one used in the backend system, django's make_key() function will do this.
https://docs.djangoproject.com/en/1.8/topics/cache/#cache-key-transformation
>>> from django.core.cache import caches
>>> caches['default'].make_key('test-key')
u':1:test-key'
Solution 4
Switch to using LocMemCache instead of MemcachedCache:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
}
}
Then see the question Contents of locmem cache in Django?:
from django.core.cache.backends import locmem
print(locmem._caches)
Solution 5
The Memcached documentation recommends that instead of listing all the cache keys, you run memcached in verbose mode and see everything that gets changed. You should start memcached like this
memcached -vv
and then it will print the keys as they get created/updated/deleted.
Brenden
Updated on November 10, 2021Comments
-
Brenden over 2 years
I'm trying to understand how Django is setting keys for my views. I'm wondering if there's a way to just get all the saved keys from Memcached. something like a
cache.all()
or something. I've been trying to find the key withcache.has_key('test')
but still cant figure out how the view keys are being named.UPDATE: The reason I need this is because I need to manually delete parts of the cache but dont know the key values Django is setting for my cache_view key
-
Karam Haj over 4 years'RedisCache' object has no attribute 'keys'
-
Eduard Mukans almost 4 years@KaramHaj I think for newer versions you can try to use
cache.get('*')
-
Nwawel A Iroume almost 3 years@KaramHaj
cache.get('*')
returnsNone
instead of every keys likecache.keys('*')
. Tested on django 3.2.3 and redis 3.5.3 -
JJK about 2 yearsThis is the answer I was looking for.
-
JJK about 2 yearsThis answer does not work for
RedisCache
that is provided by Django 4+ See my answer below for more details. -
JJK about 2 yearsNote this does not work for the RedisCache backend that is provided with Django>=4. See my answer below for more details.
-
softarn about 2 yearsAh yea, django 3.2 here