What is a domain-organized Django large project structure?
A domain-organized structure gives each bounded context its own Django app: billing, catalog, fulfillment, identity. Each app owns its models, services, views, and migrations. The alternatives scale poorly. Layer-based packages (models/, views/, serializers/) scatter one business change across the whole tree. One-app-per-model produces dozens of tiny apps that all import each other.
myproject/
├── config/ # settings, root urls.py, asgi.py, wsgi.py
├── domains/
│ ├── identity/
│ ├── catalog/
│ ├── billing/
│ └── fulfillment/
└── shared/ # small kernel: money, ids, base classes
Allowed dependencies:
config ──► domains/* ──► shared
│
└─► other domain's public interface only
shared ──► (nothing in domains/)
The config package only wires things together. It loads settings, mounts each domain's URLconf, and exposes the ASGI/WSGI entry points. It contains no business logic.
The layout matters less than the rules about dependencies. You can rename domains/ or flatten it, and nothing important changes. If billing reaches into fulfillment's internals, the structure is decoration. The boundary is the arrows in the diagram, not the folders. Later sections cover how to make those arrows enforceable.
shared is where most of these designs decay. It turns into a dumping ground because it is the one place every domain is allowed to import from. Keep it small with three constraints:
- No domain concepts. Value types like
MoneyorEmailAddressbelong inshared.InvoiceandCustomerdo not. - No imports from
domains/. If shared code needs a domain model, it is not shared. - A promotion bar. Code moves into
sharedonly after at least two domains need it in identical form. Code-review ownership should treat additions tosharedas API changes.
┌──────────────────────────────────────────────────────────────────┐
│ config/ settings · root urls.py · asgi.py · wsgi.py · no logic │
└──────┬───────────────┬───────────────┬────────────────────┬──────┘
│ include(urls) │ │ │
▼ ▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ identity │ │ catalog │ │ billing │ │ fulfillment │
├─────────────┤ ├─────────────┤ ├─────────────┤ ├─────────────┤
│ public API │ │ public API │ │ public API │ ┌──►│ public API │
├─────────────┤ ├─────────────┤ ├─────────────┤ │ ├─────────────┤
│ models │ │ models │ │ services ───┼──┘ │ models │
│ services │ │ services │ │ models ───┼──╳──►│ services │
│ views │ │ views │ │ views │ │ views │
│ migrations │ │ migrations │ │ migrations │ │ migrations │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │ │
▼ ▼ ▼ ▼
┌──────────────────────────────────────────────────────────────────┐
│ shared/ Money · EmailAddress · ids · base classes │
│ no domain concepts · no imports from domains/ │
│ promoted only when 2+ domains need it │
└──────────────────────────────────────────────────────────────────┘
──► allowed import ─╳─► forbidden: another domain's internals
shared/ never points upward: it imports nothing from domains/
Dependencies flow one way: config wires each domain's URLs, domains depend on shared and only on another domain's public API, and shared depends on no domain.
How do you identify domain boundaries for Django apps?
Start from what the business does, not from what the code is. A useful test is vocabulary: if billing staff say "invoice," "credit note," and "dunning," and nobody else does, those terms mark a boundary. When the same word means different things in different places, you have found two contexts. An "order" in fulfilment is a pick list with a shipping address. In accounting it is a revenue line with tax treatment. Forcing both into one model produces a class that every team edits and nobody owns.
| Split | Example apps | What changes together | Typical failure |
|---|---|---|---|
| Layer-based | models, api, utils, services |
One feature touches every app | Every PR spans the whole tree; no clear owner |
| Domain-based | billing, catalog, fulfilment |
One feature stays inside one app | Boundaries drawn wrongly early become costly to move |
An existing codebase shows you where its boundaries are misplaced. Look for:
- Dense cross-app imports. Two apps that import each other's models or internals heavily are one domain.
- Co-changing models. If commits routinely touch models in two apps at once, the boundary cuts through a single concept.
- Shared-model churn. A model that many apps extend with nullable fields is absorbing several meanings.
- Overloaded terms. Fields like
statusortypewhose valid values depend on the caller.
Do not draw boundaries too early or too finely. Django ties each model's table name, migrations, content types, and permissions to its app label. Moving a model between apps later means hand-written migrations and coordinated data changes. Many small apps that call each other constantly give you that cost with no gain in isolation. Start coarse and split only when the signals above appear.
How does a domain app work internally and expose a public interface?
Inside a domain app, each module has one job. models.py holds the tables. services.py holds business logic and every write: functions like place_order(customer_id, items) that validate, run inside transaction.atomic(), and save. selectors.py holds reads, such as get_order_summary(order_id), so query shape and select_related choices live in one place instead of being scattered across views. Views, serializers and admin stay thin. They parse input, call a service or selector, and format output. With that split, a business rule has one home and can be tested without an HTTP request.
Other domains import only from a small public.py (or the package's __init__.py). It re-exports a few service and selector functions, and those functions return frozen dataclasses such as OrderSummary(id, total, status) instead of model instances. Returning dataclasses matters: if billing receives an Order model, it can follow relations, call .save(), or trigger lazy queries, and your schema becomes its contract. A caller in billing would call orders.public.get_order_summary(order_id) and use only the fields it gets back. Everything else in the app is private by convention.
Python cannot enforce that privacy. Any module can still import orders.models, so the boundary holds only through review and tooling (covered later).
The pattern adds overhead. For a domain that is plain CRUD, services and selectors that just wrap Model.objects add extra files and extra call hops without protecting anything. Use the pattern where real business logic lives.
# orders/types.py -- plain data handed to other domains, never model instances
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class OrderSummary:
id: int
total: Decimal
status: str
# orders/selectors.py -- reads; query shape lives here, not in views
def get_order_summary(order_id: int) -> OrderSummary:
order = Order.objects.only("id", "total", "status").get(pk=order_id)
return OrderSummary(id=order.pk, total=order.total, status=order.status)
# orders/services.py -- business rules and every write
from django.db import transaction
def place_order(customer_id: int, items: list[dict]) -> OrderSummary:
if not items:
raise ValueError("An order needs at least one item")
total = sum(i["unit_price"] * i["qty"] for i in items)
with transaction.atomic(): # order and lines are saved together or not at all
order = Order.objects.create(customer_id=customer_id, total=total, status="placed")
OrderLine.objects.bulk_create([OrderLine(order=order, **i) for i in items])
return OrderSummary(id=order.pk, total=order.total, status=order.status)
# orders/public.py -- the only module other apps may import (convention, not enforced)
from orders.selectors import get_order_summary
from orders.services import place_order
from orders.types import OrderSummary
# billing/services.py -- a caller in another domain
from orders import public as orders
def create_invoice(order_id: int) -> Invoice:
summary = orders.get_order_summary(order_id) # gets fields, not an Order it could .save()
if summary.status != "placed":
raise ValueError("Only placed orders can be invoiced")
return Invoice.objects.create(order_id=summary.id, amount=summary.total)
A minimal orders domain with a frozen dataclass, a selector, and a transactional service, all re-exported through public.py, and a billing service that imports only that public surface. Model imports such as Order and Invoice are omitted for brevity.
Should you use ForeignKeys across Django apps in a bounded context design?
A ForeignKey from billing.Invoice to accounts.User creates a hard dependency. makemigrations records the accounts migration as a dependency of the billing migration, so the upstream app must be installed and migrated first. Any rename or table split in accounts then forces changes in billing. This coupling is acceptable in two cases:
- The upstream context is stable and nearly everything depends on it. Identity is the usual example, which is why pointing at
settings.AUTH_USER_MODELis normal. - The relationship must be strongly consistent. For example, an order line must never reference a product row that does not exist.
In other cases, store the identifier, for example customer_id = models.UUIDField(db_index=True) instead of models.ForeignKey("crm.Customer", ...). The owning domain keeps control of its schema, and the dependency moves out of the migration graph and into a function you call.
You give up three things:
- Referential integrity. The database no longer rejects orphaned rows or cascades deletes, so you need cleanup jobs or reactions to domain events.
- Joins.
select_relatedcannot cross the boundary. - Query safety. A template loop that fetches each customer one at a time becomes an N+1 query.
To compensate, write batching selectors that accept a list of IDs and return a dict, such as get_customers_by_ids(ids), and call them once per page.
| Concern | Cross-app ForeignKey | Stored identifier |
|---|---|---|
| Migration coupling | Upstream migration becomes a dependency | None |
| Referential integrity | Enforced by the database | Enforced by application code |
| Fetching related data | select_related join |
Batched selector call |
| N+1 risk | Low with select_related |
Higher without batching |
| Best fit | Identity, strongly consistent data | Most other cross-domain references |
# billing/models.py
from django.conf import settings
from django.db import models
class Invoice(models.Model):
# Acceptable cross-app FK: identity is stable and everything depends on it.
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
# Stored identifier: crm owns its schema; no migration dependency on crm.
customer_id = models.UUIDField(db_index=True)
total = models.DecimalField(max_digits=12, decimal_places=2)
# crm/selectors.py -- the public read API of the crm context
from crm.models import Customer
def get_customers_by_ids(ids):
# One query for the whole batch; returns {id: Customer}.
return {c.id: c for c in Customer.objects.filter(id__in=set(ids))}
# billing/views.py
from crm.selectors import get_customers_by_ids
def invoice_rows():
# FK side: select_related joins the user in the same query.
invoices = list(Invoice.objects.select_related("created_by")[:50])
# Identifier side: one batched call per page instead of one query per row.
customers = get_customers_by_ids(inv.customer_id for inv in invoices)
return [
(inv, inv.created_by, customers.get(inv.customer_id)) # None if orphaned
for inv in invoices
]
An Invoice model that uses a ForeignKey to the stable user model and a stored UUID for the CRM customer, with a batching selector that avoids N+1 queries when loading customers for a page of invoices.
How should domains trigger side effects in other domains?
When billing must react to an order being placed, the direct service call is the clearest choice. If orders.services.place_order calls billing.services.open_invoice, the dependency is visible in the code, shows up in a stack trace, and can be followed with "go to definition." Use it when the caller actually needs the side effect to happen, and needs it to happen now.
Django signals remove the import, but the dependency is still there. Nothing at the call site shows that post_save on Order creates an invoice. Receivers are wired up at import time, typically in AppConfig.ready(), and run synchronously in an order that is hard to see. post_save also fires inside the open transaction, before commit, so a receiver that sends email or calls an API can act on data that is later rolled back.
An explicit in-process dispatcher fixes both problems. The publishing domain emits a named event, handlers are registered in one place you can search, and dispatch is wrapped in transaction.on_commit. That callback runs only after the outermost atomic block commits and is discarded on rollback.
Task queues offload slow work, but enqueue from on_commit. Otherwise a worker may load a row that isn't committed yet. A crash between the commit and the enqueue still loses the event. If that matters, write events to an outbox table in the same transaction.
| Option | Coupling | Visibility | Transaction behavior |
|---|---|---|---|
| Direct service call | Explicit import | High | Runs inside caller's transaction |
| Django signal | Hidden | Low | Fires before commit |
Explicit dispatch + on_commit |
Event contract | Medium–high | After commit; dropped on rollback |
Task queue via on_commit |
Event or task name | Medium | Async after commit; crash gap unless outbox |
# events.py: one searchable registry for cross-domain handlers
from collections import defaultdict
from functools import partial
from django.db import transaction
_handlers = defaultdict(list)
def subscribe(event_name):
def register(fn):
_handlers[event_name].append(fn)
return fn
return register
def publish(event_name, **payload):
# Defer each handler until the outermost atomic block commits.
# If the transaction rolls back, Django discards these callbacks.
for handler in _handlers[event_name]:
transaction.on_commit(partial(handler, **payload))
# billing/handlers.py (import it from BillingConfig.ready() so it registers)
@subscribe("order.placed")
def open_invoice_for_order(order_id):
# The payload carries IDs, not model instances. Committed data is re-read here.
from billing.services import open_invoice
open_invoice(order_id=order_id)
# orders/services.py
def place_order(cart):
with transaction.atomic():
order = Order.objects.create(customer=cart.customer, total=cart.total)
# The event is declared at the call site but runs only after commit.
publish("order.placed", order_id=order.pk)
return order
A minimal in-process event registry where publish schedules each handler with transaction.on_commit, so billing opens an invoice only after the order's transaction commits.
How do you enforce boundaries and migrate a tangled Django project?
Boundaries that exist only in a diagram erode within weeks. Enforce them in CI with import-linter. An independence contract declares that a set of domain packages must not import each other's internals. A layers contract lets api modules depend on services, which depend on models, but never the reverse. Pair this with a CODEOWNERS file that maps each app directory to its owning team, so changes to billing/ require billing review. Treat each ignore_imports entry as debt. A contract with forty exceptions passes CI while describing a system that does not exist.
Migrating a tangled project works incrementally:
- Map the import graph. Import-linter or a simple AST script shows which apps reach into which.
- Pick one domain. Choose the one with the fewest inbound dependencies and a clear owner.
- Build its public interface. Write service functions and data types that cover what callers actually use.
- Redirect callers. Move callers to that interface, then add the contract so they cannot regress.
- Move models last. Set
Meta.db_tableto the existing table name, or useSeparateDatabaseAndStateto change Django's model state without touching the schema.
Model moves change the app_label, and several things depend on it:
ContentTyperows are keyed byapp_label.- Permission codenames are tied to those content types, so group and user grants silently detach.
- Generic relations store
content_type_idvalues that now point at a stale row. - Other apps' migrations reference the old label in their dependencies.
Write data migrations to update the affected rows, and test them against a production-sized copy.
For tests, cover each app through its public interface only, then add a small set of cross-domain workflow tests, such as signup through first invoice, to catch broken integration.
When should you avoid domain-structured Django, and what are the alternatives?
Domain structure pays off when several teams change the same codebase and the business rules are complex enough that ownership matters. Billing, fulfilment and identity each have their own vocabulary and invariants, so clear boundaries reduce the number of people who must understand each change.
Skip it for small projects, CRUD-heavy admin tools, single-team codebases, or products whose domains are still shifting. Drawing boundaries before you understand the business tends to lock in the wrong ones, and redrawing them later costs more than keeping a flat layout.
| Approach | Fits when | Main trade-off |
|---|---|---|
| Default flat apps | One team, simple models | Boundaries erode silently |
| Layer-based packages (models, services, views) | Small codebase, shared logic | Every feature touches every layer |
| Modular monolith with stricter tooling | Many teams, need enforced rules | Tooling and CI upkeep |
| Separate services | Independent scaling or release cadence is required | Network calls, distributed data, operational load |
A domain-structured monolith still shares one database, one deploy and one process. It does not let you scale billing separately from search. Extracting a service later still means untangling shared transactions and data, so good structure helps but does not make extraction easy.
The cost is upfront: more design discussion and stricter review. The return is clearer ownership, smaller blast radius, faster onboarding and fewer merge conflicts. Illustrative estimate: if eight engineers each lose two hours a week to cross-team conflicts, halving that recovers eight hours weekly.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to django large project structure, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.