django-constance
django-constance copied to clipboard
Making CONSTANCE_DATABASE_CACHE_BACKEND tenant aware
Describe the problem
I have added constance in my TENANT_APPS that will create constance tables for each tenant in db. But in case of caching, the redis is shared between tenants. How can I make the caching of constance config tenant aware?
What exactly tenant library do you use? You can use database backend and it should work out of box. May be this option for cache help backend https://docs.djangoproject.com/en/4.1/ref/settings/#std-setting-CACHES-KEY_PREFIX
I had similar issue with django-tenants. The database worked perfectly as connection hits the constance_config table in correct schema for tenant. However when I cache in Redis it has key collision. As tenants share an instance of django KEY_PREFIX doesn't not solve issue. I worked around with the following and pointed CONSTANCE_BACKEND at this class.
from constance.backends.database import DatabaseBackend
from django.db import connection
class ConstanceTenantDatabaseBackend(DatabaseBackend):
def add_prefix(self, key):
tenant = connection.tenant
return "%s:%s:%s" % (tenant.schema_name, self._prefix, key)