Using django-tenants

Creating a Tenant

Creating a tenant works just like any other model in django. The first thing we should do is to create the public tenant to make our main website available. We’ll use the previous model we defined for Client.

from customers.models import Client, Domain

# create your public tenant
tenant = Client(schema_name='public',
                name='Schemas Inc.',

# Add one or more domains for the tenant
domain = Domain()
domain.domain = '' # don't add your port or www here! on a local server you'll want to use localhost here
domain.tenant = tenant
domain.is_primary = True

Now we can create our first real tenant.

from customers.models import Client, Domain

# create your first real tenant
tenant = Client(schema_name='tenant1',
                name='Fonzy Tenant',
                on_trial=True) # migrate_schemas automatically called, your tenant is ready to be used!

# Add one or more domains for the tenant
domain = Domain()
domain.domain = '' # don't add your port or www here!
domain.tenant = tenant
domain.is_primary = True

Because you have the tenant middleware installed, any request made to will now automatically set your PostgreSQL’s search_path to tenant1, public, making shared apps available too. The tenant will be made available at request.tenant. By the way, the current schema is also available at connection.schema_name, which is useful, for example, if you want to hook to any of django’s signals.

Any call to the methods filter, get, save, delete or any other function involving a database connection will now be done at the tenant’s schema, so you shouldn’t need to change anything at your views.

Deleting a tenant

You can delete tenants by just deleting the entry via the Django ORM. There is a flag that can set on the tenant model called auto_drop_schema. The default for auto_drop_schema is False. WARNING SETTING AUTO_DROP_SCHEMA TO TRUE WITH DELETE WITH TENANT!


There are several utils available in django_tenants.utils that can help you in writing more complicated applications.


This is a context manager. Database queries performed inside it will be executed in against the passed schema_name. (with statement)

from django_tenants.utils import schema_context

with schema_context(schema_name):
    # All commands here are ran under the schema `schema_name`

# Restores the `SEARCH_PATH` to its original value

You can also use schema_context as a decorator.

from django_tenants.utils import schema_context

def my_func():
  # All commands in this function are ran under the schema `schema_name`

This context manager is very similar to the schema_context function, but it takes a tenant model object as the argument instead.

from django_tenants.utils import tenant_context

with tenant_context(tenant):
    # All commands here are ran under the schema from the `tenant` object

# Restores the `SEARCH_PATH` to its original value

You can also use tenant_context as a decorator.

from django_tenants.utils import tenant_context

def my_func():
  # All commands in this function are ran under the schema from the `tenant` object


There are number of signals

`post_schema_sync` will get called after a schema gets created from the save method on the tenant class.

`schema_needs_to_be_sync` will get called if the schema needs to be migrated. `auto_create_schema` (on the tenant model) has to be set to False for this signal to get called. This signal is very useful when tenants are created via a background process such as celery.

`schema_migrated` will get called once migrations finish running for a schema.

`schema_migrate_message` will get called after each migration with the message of the migration. This signal is very useful when for process / status bars.


@receiver(schema_needs_to_be_sync, sender=TenantMixin)
def created_user_client_in_background(sender, **kwargs):
    client = kwargs['tenant']
    print ("created_user_client_in_background %s" % client.schema_name)
    from clients.tasks import setup_tenant
    task = setup_tenant.delay(client)

@receiver(post_schema_sync, sender=TenantMixin)
def created_user_client(sender, **kwargs):

    client = kwargs['tenant']

    # send email to client to as tenant is ready to use

@receiver(schema_migrated, sender=run_migrations)
def handle_schema_migrated(sender, **kwargs):
    schema_name = kwargs['schema_name']

    # recreate materialized views in the schema

@receiver(schema_migrate_message, sender=run_migrations)
def handle_schema_migrate_message(**kwargs):
    message = kwargs['message']
    # recreate materialized views in the schema

Multi-types tenants

It is also possible to have different types of tenants. This is useful if you have two different types of users for instance you might want customers to use one style of tenant and suppliers to use another style. There is no limit to the amount of types however once the tenant has been set to a type it can’t easily be convert to another type. To enable multi types you need to change the setting file and add an extra field onto the tenant table.

In the setting file `SHARED_APPS`, `TENANT_APPS` and `PUBLIC_SCHEMA_URLCONF` needs to be removed.

The following needs to be added to the setting file

MULTI_TYPE_DATABASE_FIELD = 'type'  # or whatever the name you call the database field

    "public": {  # this is the name of the public schema from get_public_schema_name
        "APPS": ['django_tenants',
                  # shared apps here
        "URLCONF": "tenant_multi_types_tutorial.urls_public", # url for the public type here
    "type1": {
        "APPS": ['django.contrib.contenttypes',
                 # type1 apps here
        "URLCONF": "tenant_multi_types_tutorial.urls_type1",
    "type2": {
        "APPS": ['django.contrib.contenttypes',
                 # type1 apps here
        "URLCONF": "tenant_multi_types_tutorial.urls_type2",

Now you need to change the install app line in the settings file

for schema in TENANT_TYPES:
    INSTALLED_APPS += [app for app in TENANT_TYPES[schema]["APPS"] if app not in INSTALLED_APPS]

You also need to make sure that `ROOT_URLCONF` is blank

The tenant tables needs to have the following field added to the model

from django_tenants.utils import get_tenant_type_choices

class Client(TenantMixin):
    type = models.CharField(max_length=100, choices=get_tenant_type_choices())

That’s all you need to add the multiple types.

There is an example project called `tenant_multi_types`

Other settings


By default if you look at the admin all the tenant apps will be colored dark green you can disable this by doing.



You can get the tenant domain name by calling a method on the tenant model called reverse.

Management commands

Every command except tenant_command runs by default on all tenants. You can also create your own commands that run on every tenant by inheriting BaseTenantCommand. To run only a particular schema, there is an optional argument called --schema.

Custom command example:

from import BaseTenantCommand
# rest of your imports

class Command(BaseTenantCommand):
    COMMAND_NAME = 'awesome command'
    # rest of your command
./ migrate_schemas --schema=customer1


We’ve also packed the django migrate command in a compatible way with this app. It will also respect the SHARED_APPS and TENANT_APPS settings, so if you’re migrating the public schema it will only migrate SHARED_APPS. If you’re migrating tenants, it will only migrate TENANT_APPS.

./ migrate_schemas

The options given to migrate_schemas are also passed to every migrate. Hence you may find handy

./ migrate_schemas --list


./ migrate_schemas myapp 0001_initial --fake

in case you’re just switching your myapp application to use South migrations.

migrate_schemas in Parallel

You can run tenant migrations in parallel like this:

python migrate_schemas --executor=multiprocessing

In fact, you can write your own executor which will run tenant migrations in any way you want, just take a look at django_tenants/migration_executors.

The multiprocessing executor accepts the following settings:

  • TENANT_MULTIPROCESSING_MAX_PROCESSES (default: 2) - maximum number of processes for migration pool (this is to avoid exhausting the database connection pool)

  • TENANT_MULTIPROCESSING_CHUNKS (default: 2) - number of migrations to be sent at once to every worker


To run any command on an individual schema, you can use the special tenant_command, which creates a wrapper around your command so that it only runs on the schema you specify. For example

./ tenant_command loaddata

If you don’t specify a schema, you will be prompted to enter one. Otherwise, you may specify a schema preemptively

./ tenant_command loaddata --schema=customer1


To run any command on an every schema, you can use the special all_tenants_command, which creates a wrapper around your command so that it run on every schema. For example

./ all_tenants_command loaddata


The command create_tenant_superuser is already automatically wrapped to have a schema flag. Create a new super user with

./ create_tenant_superuser --username=admin --schema=customer1


The command create_tenant creates a new schema

./ create_tenant --schema_name=new_tenant --name=new_tenant --description="New tenant"

The argument are dynamic depending on the fields that are in the TenantMixin model. For example if you have a field in the TenantMixin model called company you will be able to set this using –company=MyCompany. If no argument are specified for a field then you be promted for the values. There is an additional argument of -s which sets up a superuser for that tenant.


The command delete_tenant deletes a schema

./ delete_tenant

Warning this command will delete a tenant and PostgreSQL schema regardless if auto_drop_schema is set to False.


The command clone_tenant clones a schema.

./ clone_tenant

There are some options to that can be set. You can view all the options by running

./ clone_tenant -h

Credits to pg-clone-schema.


The command rename_schema renames a schema in the db and updates the Client associated with it.

./ rename_schema

It will prompt you for the current name of the schema, and what it should be renamed to.

You can provide them with these arguments:

./ rename_schema --rename_from old_name --rename_to new_name


If you want to run PostGIS add the following to your Django settings file

ORIGINAL_BACKEND = "django.contrib.gis.db.backends.postgis"

Performance Considerations

The hook for ensuring the search_path is set properly happens inside the DatabaseWrapper method _cursor(), which sets the path on every database operation. However, in a high volume environment, this can take considerable time. A flag, TENANT_LIMIT_SET_CALLS, is available to keep the number of calls to a minimum. The flag may be set in as follows:


When set, django-tenants will set the search path only once per request. The default is False.


The optional TenantContextFilter can be included in settings.LOGGING to add the current schema_name and domain_url to the logging context.

    'filters': {
        'tenant_context': {
            '()': 'django_tenants.log.TenantContextFilter'
    'formatters': {
        'tenant_context': {
            'format': '[%(schema_name)s:%(domain_url)s] '
            '%(levelname)-7s %(asctime)s %(message)s',
    'handlers': {
        'console': {
            'filters': ['tenant_context'],

This will result in logging output that looks similar to:

[] DEBUG 13:29 django.db.backends: (0.001) SELECT ...

Running in Development

If you want to use django-tenant in development you need to use a fake a domain name. All domains under the TLD .localhost will be routed to your local machine, so you can use things like tenant1.localhost and tenant2.localhost.

Migrating Single-Tenant to Multi-Tenant


The following instructions may or may not work for you. Use at your own risk!

  • Create a backup of your existing single-tenant database, presumably non PostgreSQL:

./ dumpdata --all --indent 2 > database.json
  • Edit to connect to your new PostrgeSQL database

  • Execute migrate to create all tables in the PostgreSQL database

  • Ensure newly created tables are empty:

./ sqlflush | ./ dbshell
  • Load previously exported data into the database:

./ loaddata --format json database.json
  • Create the public tenant:

./ create_tenant

At this point your application should be multi-tenant aware and you may proceed creating more tenants.

Third Party Apps


Support for Celery is available at tenant-schemas-celery.


django-debug-toolbar routes need to be added to (both public and tenant) manually.

from django.conf import settings
from django.conf.urls import include

if settings.DEBUG:
    import debug_toolbar

    urlpatterns += patterns(
        url(r'^__debug__/', include(debug_toolbar.urls)),

Useful information

If you want to run some code on every tenant you can do the following