Let’s walk through the basic steps to implement multitenancy in Django using the Shared Database, Shared Schema approach.
1. Create a Django Project
First, create a new Django project if you don’t already have one:
django-admin startproject multitenant_project
cd multitenant_project
2. Install Required Packages
To simplify multitenancy, you can use the django-tenants package, which provides ready-to-use tools for managing tenants.
pip install django-tenants
3. Set Up Your Django Project for Multitenancy
Next, you'll need to update your settings.py to use django-tenants. Begin by adding it to the INSTALLED_APPS:
INSTALLED_APPS = [
# Add the tenant-aware apps here
'django_tenants',
'your_app_name', # Replace with your app's name
# Django's default apps
'django.contrib.admin',
'django.contrib.auth',
...
]
Additionally, you’ll need to configure the DATABASES settings to support tenant isolation. In a shared schema setup, tenants will be identified based on a unique schema per tenant.
4. Create the Tenant Model
In Django’s multitenancy architecture, you typically need to define a Tenant model to store tenant-specific information (e.g., tenant name, domain). Using django-tenants, it’s common to subclass TenantMixin to add fields like domain, name, and schema name.
from django.db import models
from django_tenants.models import TenantMixin
class Tenant(TenantMixin):
name = models.CharField(max_length=100)
domain = models.CharField(max_length=255)
# Add any other tenant-specific fields here
5. Middleware for Tenant Identification
You’ll need middleware to identify the current tenant based on the request. django-tenants simplifies this by providing a TenantMiddleware that reads the tenant from the subdomain or domain of the request.
MIDDLEWARE = [
'django_tenants.middleware.TenantMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
6. Set Up the Tenant-Specific Database
You’ll need to create the schema for each tenant. With django-tenants, you can migrate a schema for a new tenant easily.
python manage.py migrate_schemas --shared
This command migrates your database schema for the shared tables (like user models, etc.). Each tenant will have its own schema in the same database.
7. Add Tenant-Specific Views and Data Models
After setting up tenants and schema, you'll typically have tenant-specific models and views. For example, a UserProfile model could store tenant-specific user data:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE)
# Other fields...
8. Testing and Debugging
Finally, ensure that your setup works by creating a new tenant through the Django admin panel and verifying that tenant-specific data is being handled properly