django-multitenant
raw JSON → 4.1.1 verified Fri May 01 auth: no python
Django library to implement multi-tenant databases, primarily targeting Citus (PostgreSQL extension for horizontal scaling). Supports Django 3.2 to 5.0 with Python 3.8+. Provides mixins, managers, and utilities to isolate tenant data via a tenant_id column. Release cadence is irregular, with the latest stable version 4.1.1 from 2024.
pip install django-multitenant Common errors
error AttributeError: module 'django_multitenant.models' has no attribute 'TenantModelMixin' ↓
cause TenantModelMixin was moved to django_multitenant.mixins in v3.0.0.
fix
Change import to: from django_multitenant.mixins import TenantModelMixin
error django.db.utils.ProgrammingError: column "tenant_id" of relation "myapp_project" does not exist ↓
cause The model uses TenantModelMixin but does not have a ForeignKey to the Tenant model, or the tenant field is missing.
fix
Add a ForeignKey field to the Tenant model on your tenant-aware models: tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE)
error AssertionError: Tenant id is not set ↓
cause The middleware or code did not set the current tenant via set_current_tenant() before a query.
fix
In your view or middleware, call: from django_multitenant.utils import set_current_tenant; set_current_tenant(tenant_instance)
Warnings
breaking In v3.0.0, TenantModelMixin was moved from django_multitenant.models to django_multitenant.mixins. Old imports will break. ↓
fix Change import to from django_multitenant.mixins import TenantModelMixin
gotcha TenantModelMixin must be listed before models.Model in the class definition to avoid MRO issues. ↓
fix class MyModel(TenantModelMixin, models.Model): ...
gotcha When using ManyToMany fields between tenant models, the intermediate table may not include the tenant column automatically. You must define a through model with tenant_id. ↓
fix Explicitly define a through model with a ForeignKey to the tenant model.
deprecated The TenantModel base class is deprecated in favor of TenantModelMixin + models.Model. ↓
fix Use TenantModelMixin with models.Model instead of inheriting TenantModel.
Imports
- TenantModelMixin wrong
from django_multitenant.models import TenantModelMixincorrectfrom django_multitenant.mixins import TenantModelMixin - TenantManager
from django_multitenant.managers import TenantManager
Quickstart
import os
from django.db import models
from django_multitenant.mixins import TenantModelMixin
from django_multitenant.models import TenantModel
class Tenant(models.Model):
tenant_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Project(TenantModelMixin, models.Model):
tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
class Meta:
app_label = 'myapp'
# In your settings, ensure DATABASES and MIDDLEWARE are configured
# See https://django-multitenant.readthedocs.io/