Skip to content
rg2019 edited this page May 10, 2019 · 2 revisions

Let's do it

1. You need install django-db-multitenant for this you can use the terminal and using pip:

pip install django-db-multitenant

2. Add your custom mapper in this case i'm going to show you an example to MySQL:

from db_multitenant import mapper

class TenantMapper(mapper.TenantMapper): def get_tenant_name(self, request): """get the first part from the host as tenant name """ hostname = request.get_host().split(':')[0].lower() return hostname.split('.')[0]

`def get_db_name(self, request, tenant_name):`
    `return 'example-%s' % tenant_name`

`def get_cache_prefix(self, request, tenant_name, db_name):`
    `return 'example-%s' % tenant_name`

in this step i suggest use a method for get the Absolute URL and then use split to get REAL TENANT example, if my url is "localhost/myclient1":

def get_db_name(self, request, tenant_name): result = request.get_full_path().split('/') print result #this maybe return something like this ['localhost', 'myclient1'] return result[1] #here say to Tenant use the myclient1

the same for get_cache_prefix .

3. Add MULTITENANT_MAPPER_CLASS on settings.py:

MULTITENANT_MAPPER_CLASS = 'myapp.mapper.TenantMapper'

4.- Add MIDDLEWARE_CLASSES in settings.py as the first middleware of the list:

MIDDLEWARE = [ 'db_multitenant.middleware.MultiTenantMiddleware', .... ]

5.- Change database backend in settings.py:

DATABASES = { 'default': { 'ENGINE': 'db_multitenant.db.backends.mysql', 'NAME': 'my_db_default', ..... } }

6.- Add Cache in settings.py:

CACHES = { 'default' : { 'LOCATION': '127.0.0.1:11211', 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'KEY_FUNCTION': 'db_multitenant.cache.helper.multitenant_key_func' } }

7.- Little Hack add this at the end of file settings.py:

from db_multitenant.utils import update_from_env update_from_env(database_settings=DATABASES['default'], cache_settings=CACHES['default'])

8.- Migrate on the termina type this(name of DB for each client):

TENANT_DATABASE_NAME=myclient1_db./manage.py migrate

9.- Runnig to start and test type this on your terminal:

TENANT_DATABASE_NAME=myclient1_db ./manage.py runserver

that's all folks

Note.- remember that in the url you determinate to which database calling is very important this example:

if i type in url "localhost:8000/client1" i'm calling to DB "client1".

Clone this wiki locally