Django database cache TIMEOUT - make backend delete row

Viewed 1555

I'm not sure what Django database cache does with expired entries but it seems that they remain in the database.

I want Django to delete them after they expire because their size is huge and there can be unlimited number of different keys.

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'cache_table',
        'TIMEOUT': 60 * 20,
    }
}

I use cache on filtered list of objects and this filter contais number and char fields.

Is it possible?

1 Answers

It isn't possible to purge expired entries as they expire. This is one of the many reasons you probably don't want to use the database cache in production!

If possible, you should switch to a different cache backend (I prefer Redis). If you can't, you do have a few other options:

  1. If you know the cache keys you want to purge, you can use the low-level cache API to directly delete the keys you want to purge.

  2. You could tweak the MAX_ENTRIES and/or CULL_FREQUENCY cache arguments to limit the overall size of the cache.

  3. You could poke into the database directly (perhaps from a background task or cron job), manually running some SQL like DELETE FROM cache_table WHERE expires < now() (I haven't tested this, but I think it should work).

Related