|
| 1 | +================ |
| 2 | +Database caching |
| 3 | +================ |
| 4 | + |
| 5 | +.. class:: django_mongodb_backend.cache.MongoDBCache |
| 6 | + |
| 7 | +You can configure :doc:`Django's caching API <django:topics/cache>` to store |
| 8 | +its data in MongoDB. |
| 9 | + |
| 10 | +To use a database collection as your cache backend: |
| 11 | + |
| 12 | +* Set :setting:`BACKEND <CACHES-BACKEND>` to |
| 13 | + ``django_mongodb_backend.cache.MongoDBCache`` |
| 14 | + |
| 15 | +* Set :setting:`LOCATION <CACHES-LOCATION>` to ``collection_name``, the name of |
| 16 | + the MongoDB collection. This name can be whatever you want, as long as it's a |
| 17 | + valid collection name that's not already being used in your database. |
| 18 | + |
| 19 | +In this example, the cache collection's name is ``my_cache_collection``:: |
| 20 | + |
| 21 | + CACHES = { |
| 22 | + "default": { |
| 23 | + "BACKEND": "django_mongodb_backend.cache.MongoDBCache", |
| 24 | + "LOCATION": "my_cache_collection", |
| 25 | + }, |
| 26 | + } |
| 27 | + |
| 28 | +Unlike other cache backends, the database cache does not support automatic |
| 29 | +culling of expired entries at the database level. Instead, expired cache |
| 30 | +entries are culled each time ``add()``, ``set()``, or ``touch()`` is called. |
| 31 | + |
| 32 | +Creating the cache collection |
| 33 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 34 | + |
| 35 | +Before using the database cache, you must create the cache collection with this |
| 36 | +command: |
| 37 | + |
| 38 | +.. code-block:: shell |
| 39 | +
|
| 40 | + python manage.py createcachecollection |
| 41 | +
|
| 42 | +.. admonition:: Didn't work? |
| 43 | + |
| 44 | + If you get the error ``Unknown command: 'createcachecollection'``, ensure |
| 45 | + ``"django_mongodb_backend"`` is in your :setting:`INSTALLED_APPS` setting. |
| 46 | + |
| 47 | +This creates a collection in your database with the proper indexes. The name of |
| 48 | +the collection is taken from :setting:`LOCATION <CACHES-LOCATION>`. |
| 49 | + |
| 50 | +If you are using multiple database caches, :djadmin:`createcachecollection` |
| 51 | +creates one collection for each cache. |
| 52 | + |
| 53 | +If you are using multiple databases, :djadmin:`createcachecollection` observes |
| 54 | +the ``allow_migrate()`` method of your database routers (see the |
| 55 | +`Multiple databases`__ section of Django's caching docs). |
| 56 | + |
| 57 | +.. __: https://docs.djangoproject.com/en/5.1/topics/cache/#multiple-databases |
| 58 | + |
| 59 | +Like :djadmin:`migrate`, :djadmin:`createcachecollection` won't touch an |
| 60 | +existing collection. It will only create missing collections. |
0 commit comments