Search code examples
djangopostgresqldjango-tenants

Change schema on views using Django Tenants


I'm using Django Tenants on my project and I'm creating a schema for each Tenant. I have 'django.contrib.auth' and 'django.contrib.contenttypes' both in SHARED_APPS and in TENANT_APPS, and now I want to create specific groups in each tenant schema. The problem is that I'm always reading and writing values from the public schema. I implemented the following:

DATABASES = {
    'default': {
        'ENGINE': 'django_tenants.postgresql_backend',
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASS',
        'HOST': 'DB_HOST',
        'PORT': 'DB_PORT',
    }
}


DATABASE_ROUTERS = (
    'django_tenants.routers.TenantSyncRouter',
)

How can I change to a different schema? Can I do it on an app views?


Solution

  • Found a solution,

    from django_tenants.utils import schema_context
    
    my_schema_name = 'volvo'
    from django_tenants.utils import schema_context
    with schema_context(my_schema_name):
       #do what you want here
    

    Basically, it was the same problem as here, but with a different library (django-tenants). After checking their source code, found out that they had the same method.