Skip to main content

Claude Prompt to Architect Django Multi-Tenancy

Implement Django multi-tenancy with tenant-aware querysets, strict data isolation, tenant middleware, shared models, and cross-tenant admin access.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Implement multi-tenancy for a B2B project management SaaS Django application serving 200+ tenants. Each tenant has 5-50 users and 10,000-500,000 records data. Design: 1) Choose and implement a tenancy strategy: shared database with tenant_id column (row-level isolation). Justify the choice based on data isolation requirements (strict — no tenant can ever see another tenants data), scalability needs, and operational complexity. 2) Tenant model with fields: name, slug, domain, plan (FK to Plan), is_active, settings (JSONField for per-tenant configuration), and created_at. Include a TenantMiddleware that resolves tenant from subdomain (acme.app.com) with fallback to X-Tenant-ID header for API and stores it in thread-local or ContextVar. 3) Tenant-aware model mixin (TenantMixin) that adds a tenant ForeignKey, overrides default manager to auto-filter by current tenant, and overrides save() to auto-set tenant from the current context. Apply to Project, Task, Document, Team, Invitation. 4) Database routing for all tenants in shared database but with schema-level separation for enterprise clients — if using separate schemas, implement a database router that directs reads/writes based on current tenant. 5) Tenant isolation verification: middleware that blocks cross-tenant data access, serializer validation that rejects foreign tenant IDs in relationships, and pytest fixture that creates 2 tenants and verifies queryset isolation test helper. 6) Shared data pattern for Plan, Feature, GlobalSetting, AdminUser — models accessible by all tenants (global settings, plan definitions, feature flags) using a separate non-tenanted manager. 7) Admin super-admin view that can switch between tenants and view cross-tenant analytics for total users, revenue per tenant, storage usage, feature adoption rates.

What this prompt does

This prompt designs multi-tenancy for a [project_type] Django app serving [tenant_count] tenants, each with [users_per_tenant] users and [data_volume] of data. It asks the AI to choose and justify a tenancy strategy ([tenancy_strategy]) against your [isolation_level] requirement, scalability needs, and operational complexity, then implement a Tenant model (name, slug, domain, plan, settings JSONField) and a TenantMiddleware that resolves the tenant from [tenant_resolution] and stores it in thread-local or a ContextVar.

The core safety mechanism is a TenantMixin applied to [tenant_scoped_models]: it adds a tenant ForeignKey, overrides the default manager to auto-filter by the current tenant, and overrides save() to set the tenant from context. It layers on isolation verification — middleware blocking cross-tenant access, serializer validation rejecting foreign tenant IDs in relationships, and a [test_isolation_method] helper — a shared non-tenanted manager pattern for [shared_models] like plans and feature flags, and a super-admin view that can switch tenants and view cross-tenant analytics for [admin_analytics].

When to use it

  • You're building B2B SaaS where tenant data must never leak across customers
  • You want an auto-filtering manager so developers can't forget the tenant filter
  • You need tenant resolution from a subdomain or a header for API clients
  • You want isolation tests that prove two tenants can't see each other's data
  • You have global data (plans, feature flags) that should bypass tenant scoping
  • You need a super-admin able to switch tenants and view cross-tenant metrics
  • You want the tenancy choice justified against your isolation and scaling needs, not assumed

Example output

The AI returns a justified strategy choice with trade-offs, a Tenant model definition, a TenantMiddleware using a ContextVar, the TenantMixin with manager and save() overrides, isolation-verification code, a separate manager for [shared_models], and an admin tenant-switcher view for [admin_analytics]. Expect a written trade-off discussion plus code blocks per numbered section, so the reasoning behind row-level isolation is explicit and reviewable.

Pro tips

  • State [isolation_level] as strict explicitly so the AI defends row-level filtering with proper enforcement rather than convention
  • Prefer a ContextVar over thread-local if any async code paths exist, since thread-local doesn't carry across async contexts cleanly
  • Always pair the auto-filtering manager with isolation tests from [test_isolation_method] — one missing filter is the bug you find in production
  • Keep [shared_models] on a separate non-tenanted manager so global config isn't accidentally scoped to a tenant
  • Make serializer validation reject foreign tenant IDs in [tenant_scoped_models] relationships, not just top-level objects
  • Reject requests with an unknown tenant from [tenant_resolution] early with a 404 rather than letting them fall through
  • If [tenant_resolution] supports both subdomain and header, define a clear precedence so requests resolve deterministically

Frequently Asked Questions

Which tenancy strategy does this prompt recommend?
It asks the AI to choose and justify a strategy via `[tenancy_strategy]`, defaulting to a shared database with a tenant_id column for row-level isolation. The justification weighs your `[isolation_level]`, scalability, and operational complexity rather than assuming one answer.
How does it stop one tenant from seeing another tenant's data?
The TenantMixin overrides the default manager to auto-filter every query by the current tenant and sets the tenant on save from context. This is backed by middleware blocking cross-tenant access and serializer validation rejecting foreign tenant IDs, so isolation isn't left to developer discipline alone.
How is the current tenant identified on each request?
The TenantMiddleware resolves the tenant from `[tenant_resolution]`, typically a subdomain with a header fallback for API clients, and stores it in thread-local or a ContextVar for downstream code. Requests with an invalid tenant are rejected with a 404.
Does it include tests to prove isolation actually works?
Yes, and this matters because a single missing filter leaks data. The prompt asks for a `[test_isolation_method]` helper, typically a fixture creating two tenants and asserting that one tenant's queryset never returns the other's records. Treat these tests as mandatory, not optional.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Django & Flask Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support