Skip to content

Caching

Django has a built-in caching system that allows you to cache your views. This is useful for speeding up your app and reducing the load on your database.

With Djipfast we create a separate database for caching.

Add the following to your settings.py file:

config/settings.py
# ...

DATABASE_ROUTERS = ['config.routers.CacheRouter']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': DATA_DIR / 'db.sqlite3',
        'OPTIONS': {
            'init_command': 'PRAGMA journal_mode=WAL; PRAGMA temp_store=MEMORY; PRAGMA synchronous=NORMAL; PRAGMA cache_size=-64000',
            'timeout': 20,
            'transaction_mode': 'IMMEDIATE',
        },
    },
    'cache': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': DATA_DIR / 'cache.sqlite3',
        'OPTIONS': {
            'init_command': 'PRAGMA journal_mode=WAL; PRAGMA temp_store=MEMORY; PRAGMA synchronous=NORMAL; PRAGMA cache_size=-64000',
            'timeout': 20,
            'transaction_mode': 'IMMEDIATE',
        },
    },
}

# -----------------------------------------------------------------------------
# Cache https://docs.djangoproject.com/en/5.1/topics/cache/
# -----------------------------------------------------------------------------

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'django_cache',
    },
}

By default Django only writes to the default database. To change this, create a config/routers.py file and add the following code:

config/routers.py
class CacheRouter:
    """A router to control all database cache operations"""
    def db_for_read(self, model, **hints):
        if model._meta.app_label == "django_cache":
            return "cache"  # This matches the database name in settings.py
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == "django_cache":
            return "cache"
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label == "django_cache":
            return db == "cache"
        return None

To create the cache.sqlite3 database, run the following command:

python manage.py createcachetable --database cache

This will create the cache.sqlite3 database file and a django_cache table.

Info

  • The cache.sqlite3 database is created in the data directory.
  • The django_cache table is created inside the cache.sqlite3 database.