What is a domain-oriented large Django project structure, and why does the default layout break down?

A domain-oriented layout groups Django apps by business capability, such as billing, catalog or fulfilment, rather than by model or technical concern. Each domain app exposes a small public interface (a services module and a few read-only query functions), and other code may import only that interface. A tool in CI enforces the rule, so it does not depend on reviewers noticing violations.

The default startapp workflow doesn't prevent this kind of structure, but it doesn't encourage it either. Teams usually drift into one of these patterns:

Layout How apps are split What goes wrong at scale
Default startapp growth Wherever the first developer put it A few apps become dumping grounds for unrelated models
One app per model orders, order_items, invoices Every feature touches several apps. ForeignKeys cross app lines constantly
One app per technical layer models, api, tasks A single feature is spread across every app, so no app has an owner
Domain-oriented One app per business capability Requires up-front boundary decisions and ongoing enforcement

The failure modes compound. When any module can import from any other app, circular imports appear, and developers work around them with function-level imports and string model references. ForeignKeys spread across apps until changing one table breaks migrations owned by another team. On-call engineers can't tell who owns a failing task, because its code lives in three places.

Multiple teams sharing one monolith benefit the most. This structure pays off once more than one team ships to the same codebase every week. It also pays off when you expect to extract a service later, because clean boundaries make extraction possible without first untangling the code.

How do you draw domain boundaries and lay out the project?

Start from business capabilities, not technical layers. Billing, accounts, catalog and fulfilment are good domains. "Models", "utils" and "API" are not. A domain should change for one business reason and have one owning team. That team reviews changes to it and decides what it exposes. When two teams regularly edit the same domain, the boundary is wrong, or the domain needs splitting.

A domain does not have to be a single Django app. Small domains fit in one app. Larger ones can be a package containing several apps, such as billing.invoices and billing.payments. They still present one public face to the rest of the project.

The layout

The project package sits at the top level and holds the domain packages. Each domain contains:

  • Models, owned exclusively by that domain.
  • A services or api module: the only thing other domains may import.
  • Internal modules (queries, tasks, adapters) that are private by convention and, later, by enforcement.
  • Its own tests, so the owning team can run them in isolation.

Next to the domains, keep a thin config package for settings, URLs and WSGI/ASGI entry points, plus a small shared kernel for genuinely universal pieces like base model mixins or money types. Avoid a catch-all common or core app. Anything without an obvious home ends up there, and soon every domain depends on it.

Settings

Split settings by environment: base, local, test, production. Read secrets and connection strings from environment variables rather than committing them. Keep domain-specific configuration, such as a payment provider timeout, in a settings module inside that domain. Then the owning team can change it without editing a global file everyone touches.

shop/                         # top-level project package
├── config/                   # thin: settings, URLs, entry points only
│   ├── settings/
│   │   ├── base.py           # shared defaults, INSTALLED_APPS
│   │   ├── local.py          # from .base import *; DEBUG = True
│   │   ├── test.py           # fast password hasher, test DB
│   │   └── production.py     # SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
│   ├── urls.py
│   ├── wsgi.py
│   └── asgi.py
├── kernel/                   # deliberately small: universal pieces only
│   ├── money.py              # Money value type
│   └── models.py             # abstract TimestampedModel mixin
├── accounts/                 # one domain = one app (owner: identity team)
│   ├── models.py
│   ├── services.py           # public interface for other domains
│   ├── _queries.py           # internal, private by convention
│   └── tests/
├── catalog/                  # owner: merchandising team
│   ├── models.py
│   ├── services.py
│   └── tests/
└── billing/                  # one domain = package of apps (owner: payments team)
    ├── api.py                # the single public face of billing
    ├── settings.py           # PAYMENT_PROVIDER_TIMEOUT_SECONDS = 10
    ├── invoices/             # Django app: billing.invoices
    │   ├── models.py
    │   ├── _tasks.py         # internal
    │   └── tests/
    └── payments/             # Django app: billing.payments
        ├── models.py
        ├── _adapters.py      # internal: payment provider client
        └── tests/

# Other domains import only the public module:
#   from shop.billing.api import create_invoice    # allowed
#   from shop.billing.invoices.models import ...   # not allowed

A domain-oriented Django layout: a thin config package with per-environment settings, a small shared kernel, and domains that are either one app or a package of apps, each exposing a single public module and keeping its own tests and local configuration.

How does a public interface per domain work in Django?

Each domain exposes one module, conventionally services.py or an api package, as the only thing other domains may import. Everything else, including models, managers and querysets, is private. When the orders domain needs a customer's billing details, it calls customers.services.get_billing_profile(customer_id) and receives a frozen dataclass such as BillingProfile(customer_id, country, tax_id). It does not import Customer and filter on it.

The return type matters more than the function. A model instance is still connected to the database. Callers can follow foreign keys, call .save() or trigger lazy queries, so the owning domain loses control over how its tables are read and written. A dataclass carries only the fields the owner chose to publish. The owner can then rename columns, split tables or add caching without breaking callers.

This approach has real costs:

  • More code. A one-line ORM query becomes a function, a dataclass and a mapping step.
  • No cross-domain joins. select_related and prefetch_related stop at the domain edge, so a single joined query becomes two or more queries.
  • N+1 queries. A loop that calls get_billing_profile once per order issues one query per row.

The main mitigation is to make interfaces batch-oriented from the start. Expose get_billing_profiles(customer_ids: list[int]) -> dict[int, BillingProfile], which runs one filter(id__in=...) query. Callers then collect IDs first and look up results second. This gives you the same query count as prefetch_related, and the boundary stays intact.

# customers/services.py -- the only module other domains may import
from dataclasses import dataclass

from customers.models import Customer  # private to the customers domain


@dataclass(frozen=True)
class BillingProfile:
    customer_id: int
    country: str
    tax_id: str | None


def get_billing_profiles(customer_ids: list[int]) -> dict[int, BillingProfile]:
    # One query for the whole batch; .values() avoids handing out model instances
    rows = Customer.objects.filter(id__in=set(customer_ids)).values(
        "id", "country", "tax_id"
    )
    return {
        r["id"]: BillingProfile(r["id"], r["country"], r["tax_id"])
        for r in rows
    }


# orders/invoicing.py -- caller in another domain
from customers import services as customers

from orders.models import Order


def build_invoice_lines(order_ids: list[int]) -> list[tuple[int, str]]:
    orders = list(Order.objects.filter(id__in=order_ids))
    # Collect IDs first, then look up once: 2 queries total, not 1 + N
    profiles = customers.get_billing_profiles([o.customer_id for o in orders])
    return [(o.id, profiles[o.customer_id].country) for o in orders]

A batch-oriented service function in the customers domain returns frozen dataclasses keyed by ID, so the orders domain fetches billing data in one query without importing the Customer model.

How can you enforce import boundaries in CI?

Run the check as an ordinary CI job that fails the build, not as a report someone reads later. You have two practical options. A static import-contract checker lets you declare rules such as "orders may import only billing.api" in configuration. A custom test parses every module with Python's ast module, collects Import and ImportFrom nodes, maps each target to its owning domain, and asserts that cross-domain targets resolve to that domain's public module. The custom test is less code than it sounds, and it lets you encode Django-specific exemptions directly.

Existing violations go in an explicit allowlist checked into the repository, with each entry recording the importing module and the imported module. Fail on any new violation. Also fail on allowlist entries that no longer occur, so the list can only shrink and nobody pads it "just in case."

Know what an import graph cannot see:

  • String model references. ForeignKey("billing.Invoice") creates a hard coupling with no import. Add a test that iterates apps.get_models() and checks each relation's related_model._meta.app_label against the same dependency rules.
  • Lazy imports inside functions. Confirm your checker walks function bodies, not only module-level statements. A full ast walk catches these.
  • Dynamic lookups. apps.get_model(), importlib.import_module() and dotted paths in settings are invisible to static analysis. Grep for them and review each one.
  • Framework couplings. Admin registrations, generic relations through ContentType, signal receivers bound to another domain's sender, and get_user_model() or AUTH_USER_MODEL all cross boundaries legitimately. Exempt each one by name with a one-line justification, rather than exempting whole files.
# tests/test_import_boundaries.py -- runs under pytest in CI; any failure fails the build.
import ast
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent / "src"
DOMAINS = {"orders", "billing", "catalog"}
# Existing debt as (importing module, imported name). This list may only shrink.
ALLOWLIST = {
    ("orders.views", "billing.models.Invoice"),
}

def violations():
    found = set()
    for path in ROOT.rglob("*.py"):
        src = ".".join(path.relative_to(ROOT).with_suffix("").parts)
        tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
        # ast.walk also visits function bodies, so lazy imports are checked too.
        for node in ast.walk(tree):
            if isinstance(node, ast.Import):
                targets = [alias.name for alias in node.names]
            elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
                targets = [f"{node.module}.{alias.name}" for alias in node.names]
            else:
                continue  # relative imports stay inside the current domain
            for target in targets:
                domain = target.split(".")[0]
                public = f"{domain}.api"
                crosses = domain in DOMAINS and domain != src.split(".")[0]
                if crosses and target != public and not target.startswith(public + "."):
                    found.add((src, target))
    return found

def test_no_new_boundary_violations():
    new = violations() - ALLOWLIST
    assert not new, f"Cross-domain imports must go through <domain>.api: {sorted(new)}"

def test_allowlist_has_no_stale_entries():
    # Remove entries once the debt is paid so nobody can reuse them later.
    stale = ALLOWLIST - violations()
    assert not stale, f"Delete fixed entries from ALLOWLIST: {sorted(stale)}"

This pytest module uses Python's ast module to walk every module, including function bodies. It fails CI when a cross-domain import bypasses the target domain's public api module, and it also fails when an allowlist entry no longer matches a real violation.

How should cross-domain data, signals and migrations be handled?

A ForeignKey across domains is acceptable when the target is stable, effectively platform-level, and genuinely needs referential integrity. The user model is the usual example: nearly every domain references it, it rarely changes shape, and AUTH_USER_MODEL already treats it as a shared contract. For anything owned by a domain that evolves independently, such as an order referenced from a shipping app, store a plain ID (an indexed integer or UUID field) and resolve it through the owning domain's public interface. You give up database-level cascades and joins. In exchange, you can change, split or move the other domain without rewriting your schema.

Use signals or an in-process event dispatcher sparingly. They decouple the sender from the receiver, but they also hide control flow. A reader of save() cannot see what runs next. Receiver ordering depends on registration order. Receivers execute inside the sender's transaction, so a failing receiver can roll back unrelated work, or a side effect can fire for data that is later rolled back. Wrap external side effects like emails, queue publishes and cache writes in transaction.on_commit. Log receiver exceptions explicitly so failures are visible.

Each app owns its migrations. Cross-app migration dependencies should be rare, because they couple deploy order. Squash only after every environment has applied the original migrations. Keep the replaced files until then. Resolve conflicting leaf nodes from parallel branches with makemigrations --merge, then review the merged result.

Moving a model between apps is expensive. You rename the table, or set db_table, and use SeparateDatabaseAndState so the state change does not drop and recreate the table. You also update ContentType rows and permission codenames that still carry the old app_label.

# shipping/models.py
import logging

from django.conf import settings
from django.db import models, transaction
from django.db.models.signals import post_save
from django.dispatch import receiver

logger = logging.getLogger(__name__)


class Shipment(models.Model):
    # Platform-level, stable target: a real FK with referential integrity is fine.
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    # Owned by the orders domain: store a plain, indexed ID, not a FK.
    # Resolve it through the orders app's public interface, never orders.models.
    order_id = models.UUIDField(db_index=True)
    status = models.CharField(max_length=20, default="pending")


def notify_carrier(shipment_id):
    # External side effect. Runs only after the transaction commits.
    try:
        from shipping.services import send_to_carrier  # placeholder service
        send_to_carrier(shipment_id)
    except Exception:
        # Don't swallow the error silently. Log it so the failure is visible.
        logger.exception("Carrier notification failed for shipment %s", shipment_id)


@receiver(post_save, sender=Shipment)
def on_shipment_created(sender, instance, created, **kwargs):
    # The receiver runs inside the sender's transaction. Defer the side effect
    # so a later rollback does not leave a carrier call for a shipment that doesn't exist.
    if created:
        transaction.on_commit(lambda: notify_carrier(instance.pk))

A shipping model keeps a ForeignKey to the user model but stores the order as a plain indexed UUID, and its post_save receiver defers the external carrier call with transaction.on_commit and logs any failure.

How do you migrate an existing tangled Django codebase incrementally?

Step by step

  1. Generate the current import graph. Use a static import-graph tool or a short script built on Python's ast module. Rank modules by how many other packages import them. Highly imported modules tell you where coupling actually lives, and that often differs from what the team believes.
  2. Pick one domain to extract first. Choose one with few inbound edges and a clear owner, such as notifications or billing. An early win proves the process without a long freeze.
  3. Add a façade module. Re-export or wrap the functions other domains need, and leave the internals where they are.
  4. Move callers over in small pull requests, one calling package at a time, so each diff stays easy to review.
  5. Lock the boundary with an import contract. Once no caller reaches into internals, enable the CI check for that domain only. Add contracts per domain as each one is cleaned up, so the rule tightens without blocking unfinished work.

Tests and fixtures

Put each domain's tests inside its app so manage.py test billing runs that domain alone. Build test data with domain-local factories instead of shared JSON fixtures. A fixture that loads orders, users and inventory just to test an invoice brings back the coupling you removed.

Where the time goes back

Engineers save time in three places. Reviewers read one domain's diff. Contract violations surface in CI instead of as another team's regression. Engineers get fast targeted test runs.

Illustrative estimate, assumed inputs: 30 engineers, a full suite of 20 minutes, a domain suite of 3 minutes, and two local runs per engineer per day. That saves 17 × 2 × 30 = 1,020 minutes, about 17 engineer-hours per day.

When should you avoid this structure, and what are the alternatives?

That payoff depends on scale, and the structure has real costs below it. Every domain facade, DTO and mapping function is indirection that a small team pays for on each change. A team of four working in a 30-model codebase may never earn back the time spent writing translation layers between apps that one person understands end to end. Drawing boundaries wrong early is worse than not drawing them. A misplaced line forces constant cross-domain calls, and moving it later means rewriting public interfaces and relocating migrations.

The structure also has hard limits. You still have one database, one deploy and one runtime. A slow migration in billing blocks a release of catalog. A memory-heavy reporting domain scales with everything else. If your actual problem is independent scaling or deployment, import boundaries do not solve it.

Approach Coupling Development cost Operational cost Team fit
Default flat apps High, implicit Lowest Lowest 1–2 small teams, early product
Layer-based (models/services/views) High across features Low Lowest Small team, CRUD-heavy domain
Modular monolith, enforced boundaries Low, explicit Moderate Low Several teams sharing one codebase
Separate services Lowest, at the network High High (deploys, observability, data consistency) Teams needing independent release or scaling

Use flat or layered apps until merge conflicts and accidental coupling slow you down measurably. Adopt enforced boundaries when multiple teams own distinct domains. Split into services only when a domain needs its own scaling profile, release cadence or failure isolation. A clean domain layout makes a later extraction cheaper, but it does not make one necessary. Many modular monoliths stay monoliths indefinitely, and that is a valid outcome.

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 large django 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.