3

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?

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

4

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).

jacobian
  • 4,648
  • 3
  • 19
  • 11
  • 1
    It seems worth noting that while the rows aren't deleted by some background process normally, the `timeout` parameter does work. It just works when the cache is read. I'm not sure if rows are deleted at that point if they're expired or not, but your client will get `None` if it tries to `get()` an expired cache entry. I just updated [the docs](https://github.com/django/django/pull/13259/files) with some info on this. – mlissner Jul 30 '20 at 20:53