Django database cache timeout – causes the backend to delete rows
I’m not sure how the Django
database cache handles expired entries, but they seem to remain in the database.
I want Django
to remove them after they expire because they are large in size and can have an unlimited number of different keys.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'cache_table',
'TIMEOUT': 60 * 20,
}
}
I use a cache
on the filtered object list, which contains numeric and character fields.
Is this possible?
Solution
Expired entries cannot be purged. This is one of the many reasons why you might not want to use database caching in production!
If possible, you should switch to a different cache backend (I prefer Redis). If not, you have some other options:
If you know which cache key to clear, you can use the low-level cache API Directly delete the key you want to clear.
You can adjust the
MAX_ENTRIES
and/orCULL_FREQUENCY
cache arguments limit the overall size of the cache.You can go directly to the database (possibly from a background task or a cron job) and manually run some SQL like
DELETE FROM cache_table WHERE expires < now() (
I haven’t tested this yet, but I think it should work).