← Back to Django, page 5

django-0091 · Hard senior

How would you implement row-level multi-tenancy in Django so that a forgotten filter cannot leak one tenant's data to another?

Add a tenant foreign key to tenant-owned models, set the current tenant per request from the hostname or token in middleware (stored in a ContextVar), and make the default manager return only the current tenant's rows. Fail closed: if no tenant is set, raise an error rather than returning everything. Back it up with composite unique constraints including the tenant, database row-level security where available, and tests that try cross-tenant access.

Full answer

Models of multi-tenancy: separate database per tenant (strongest isolation, most operational work), schema per tenant on PostgreSQL (django-tenants), or a shared schema with a tenant_id column. The shared-schema model is simplest to operate and demands discipline so queries never forget the filter.

Design:

  1. Abstract base: class TenantOwned(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE); class Meta: abstract = True.
  2. Context: current_tenant = ContextVar("tenant", default=None). Middleware resolves the tenant (subdomain, header or token claim) and sets it for the request, and resets it afterwards. ContextVars work correctly with async views and threads, unlike module globals.
  3. Manager: get_queryset() returns super().get_queryset().filter(tenant=current_tenant.get()). If the tenant is None, raise NoTenantError, so a management command or background task that forgot to set a tenant fails loudly. Provide an explicit unscoped manager for admin and migrations, and name it clearly.
  4. Auto-assignment: save() sets tenant from context if empty, and rejects a mismatch.
  5. Constraints: uniqueness per tenant: UniqueConstraint(fields=["tenant", "roll_no"], name=...). Plain unique=True on roll_no would leak existence across tenants and block valid data.
  6. Related lookups: scoped managers do not automatically apply to related-object access or select_related joins, and Model.objects.get(pk=...) from untrusted IDs is scoped only if every model uses the scoped manager. Review foreign keys: a Mark must not point to another tenant's Student (validate in clean() or with composite foreign keys).
  7. Defence in depth: PostgreSQL row-level security with SET app.tenant_id per connection or transaction; caches and file paths prefixed with the tenant; tenant in log context; Celery tasks carry tenant_id and set the context.
  8. Tests: create two tenants, fetch with the wrong tenant context, expect not found; run a test that scans all models for the tenant field.

Beware of raw SQL, bulk_* helpers on unscoped managers, and aggregated reports in admin.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from contextvars import ContextVar

from django.db import models, connection

current_tenant = ContextVar("tenant", default=None)


class NoTenantError(RuntimeError):
    pass


class TenantManager(models.Manager):
    def get_queryset(self):
        tenant = current_tenant.get()
        if tenant is None:
            raise NoTenantError("No tenant set: refusing to return unscoped data")
        return super().get_queryset().filter(tenant_id=tenant)


class Student(models.Model):
    tenant_id = models.IntegerField()
    roll_no = models.CharField(max_length=10)
    name = models.CharField(max_length=40)

    objects = TenantManager()
    unscoped = models.Manager()

    class Meta:
        app_label = "school"
        constraints = [models.UniqueConstraint(fields=["tenant_id", "roll_no"], name="uniq_roll_per_tenant")]

    def save(self, *args, **kwargs):
        tenant = current_tenant.get()
        if self.tenant_id is None and tenant is not None:
            self.tenant_id = tenant
        elif tenant is not None and self.tenant_id != tenant:
            raise NoTenantError("Cannot write another tenant's row")
        super().save(*args, **kwargs)


with connection.schema_editor() as editor:
    editor.create_model(Student)


def as_tenant(tenant_id):
    class Ctx:
        def __enter__(self):
            self.token = current_tenant.set(tenant_id)

        def __exit__(self, *exc):
            current_tenant.reset(self.token)
    return Ctx()


with as_tenant(1):
    Student(roll_no="A1", name="Asha").save()
with as_tenant(2):
    Student(roll_no="A1", name="Ravi").save()                 # same roll number is fine in another tenant
    Student(roll_no="B2", name="Kiran").save()

with as_tenant(1):
    print([s.name for s in Student.objects.all()])
with as_tenant(2):
    print([s.name for s in Student.objects.all()])
    print(Student.objects.filter(pk=1).exists(), "<- tenant 1's row id is invisible to tenant 2")

try:
    Student.objects.all()
except NoTenantError as exc:
    print("fail closed:", exc)

print(Student.unscoped.count(), "rows seen through the explicit unscoped manager")

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Asha'] ['Ravi', 'Kiran'] False <- tenant 1's row id is invisible to tenant 2 fail closed: No tenant set: refusing to return unscoped data 3 rows seen through the explicit unscoped manager

Key points

  • Choose isolation level: database, schema or shared tables
  • Tenant from middleware in a ContextVar
  • Scoped default manager that fails closed
  • Uniqueness and foreign keys must include the tenant
  • Add database RLS and tests for cross-tenant access

Common mistakes

  • Relying on developers to remember .filter(tenant=...) in every query
  • Returning all rows when no tenant is set
  • Using plain unique=True on fields that should be unique per tenant
  • Storing the tenant in a module-level global
  • Forgetting tenant context in Celery tasks and management commands

Follow-ups

  • How does PostgreSQL row-level security complement this?
  • When would you choose schema-per-tenant?
  • How do you prevent foreign keys pointing across tenants?

Tips

  • Say fail closed
  • Describe the ContextVar and middleware
  • Mention per-tenant uniqueness