Migration Guide¶
This guide helps you migrate from other Django multitenancy libraries to django-rls-tenants.
From django-tenants¶
django-tenants uses a schema-per-tenant approach. Migrating to django-rls-tenants means moving from separate schemas to a single schema with RLS policies.
Key Differences¶
| Aspect | django-tenants | django-rls-tenants |
|---|---|---|
| Isolation | Separate PostgreSQL schemas | RLS policies on shared tables |
| Tenant routing | connection.set_tenant() |
GUC variables via middleware |
| Shared apps | SHARED_APPS / TENANT_APPS |
All apps share one schema |
| Migrations | Run per-schema | Run once (single schema) |
| Raw SQL safety | Yes (schema isolation) | Yes (RLS policies) |
| Database overhead | High (N schemas) | Low (single schema) |
Migration Steps¶
-
Create a tenant FK column on all tenant-scoped tables:
-
Replace model inheritance: change
TenantMixinto your own tenant model, and tenant-scoped models to inherit fromRLSProtectedModel. -
Replace middleware: swap
TenantMainMiddlewareforRLSTenantMiddleware. -
Replace tenant routing: replace
connection.set_tenant()calls withtenant_context()oradmin_context(). -
Consolidate schemas into a single schema (this is the hardest step and is project-specific).
-
Run migrations to create RLS policies.
-
Verify: run
python manage.py check_rls.
Warning
Schema consolidation is a significant data migration and should be planned carefully. Test thoroughly in a staging environment before production.
From django-multitenant¶
django-multitenant uses ORM-level query rewriting. Migrating is simpler because you already use a single schema.
Key Differences¶
| Aspect | django-multitenant | django-rls-tenants |
|---|---|---|
| Isolation | ORM query rewriting | RLS policies |
| Raw SQL safety | No | Yes |
| Citus support | Yes | No (standard PostgreSQL) |
| Fail-closed | No | Yes |
| Manager | TenantManager |
RLSManager |
Migration Steps¶
-
Replace model base class: change
TenantModeltoRLSProtectedModel. -
Replace manager calls: change
set_current_tenant()to context managers. -
Replace middleware: swap the multitenant middleware for
RLSTenantMiddleware. -
Add
TenantUserproperties to your User model. -
Update settings: replace
MULTI_TENANTsettings withRLS_TENANTS. -
Run migrations to create RLS policies.
-
Verify: run
python manage.py check_rls.
From No Multitenancy¶
If you are adding multitenancy to an existing single-tenant application:
- Create a Tenant model (see Tenant Model).
- Add tenant FK to all data models that need isolation.
- Populate the FK with the appropriate tenant ID for existing data.
- Inherit from
RLSProtectedModelon those models. - Implement
TenantUseron your User model. - Add middleware and settings.
- Run migrations and verify with
check_rls.
The most challenging step is populating the tenant FK for existing data. Plan a data migration that assigns the correct tenant to each existing record.