What is a domain app boundary in a Django large project structure?

A domain app is a Django app that owns the writes for one business capability, such as billing, inventory or accounts, and holds a fixed position in a one-directional dependency graph. Other apps may read its data through its public interface, but only its own code creates, updates or deletes those rows. Splitting one models.py into a dozen folders without that rule gives you more directories and the same coupling.

Find boundaries before you move any code. For each model, ask which capability's code issues its writes, and group models by the answer. Then look for clusters: foreign keys that point mostly inward, and transaction.atomic blocks that touch the same tables together. If a transaction regularly spans two proposed apps, the boundary is probably in the wrong place.

Treat a shared or core app as a warning sign. Allow one only for generic code such as base model mixins, money types and time helpers. Give it a written rule: no business-specific models, no imports from domain apps, and a size limit that triggers review when exceeded.

For layout, put domain apps under one package root such as apps/ so they stay distinct from third-party apps. Keep a central settings module, because per-app settings fragments scatter configuration and make override order hard to follow. Auth, audit logging and feature flags are cross-cutting concerns. Make each its own app at the bottom of the graph, with no dependencies on domain apps. Finally, set AppConfig.label explicitly. The label defaults to the last component of the app's dotted path, so two packages both ending in orders collide. Because the label is baked into table names and migration references, renaming it later is expensive.

from django.apps import AppConfig


class SalesOrdersConfig(AppConfig):
    # Full dotted path under the apps/ package root.
    name = "apps.sales.orders"
    # Explicit label: the default would be "orders", which collides with
    # apps.purchasing.orders. The label prefixes table names and migration
    # references, so choose it once and don't change it.
    label = "sales_orders"
    default_auto_field = "django.db.models.BigAutoField"


class PurchasingOrdersConfig(AppConfig):
    name = "apps.purchasing.orders"
    label = "purchasing_orders"
    default_auto_field = "django.db.models.BigAutoField"


INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    # Cross-cutting apps at the bottom of the graph: no domain imports.
    "apps.platform.audit",
    "apps.platform.flags",
    # Generic-only shared code: mixins, money types, time helpers.
    "apps.core",
    # Domain apps: each owns the writes for one capability.
    "apps.accounts",
    "apps.inventory",
    "apps.sales.orders",
    "apps.purchasing.orders",
    "apps.billing",
]

Explicit AppConfig.label values let two apps with the same final path component, orders, coexist, and a central INSTALLED_APPS lists cross-cutting and domain apps under a single apps/ package root.

How does a domain app structure work?

Two layers make it work: what Django provides on its own, and the conventions you add on top.

Django provides the mechanics. Every entry in INSTALLED_APPS becomes an app in the app registry. Each app has its own AppConfig, its own models, and its own migrations directory. The app label namespaces table names, such as billing_invoice, and migration references, such as ("billing", "0007_..."). When the registry populates, Django imports each app's models. After that, it calls each AppConfig.ready(), which is the safe place to connect signals or register callbacks. Migrations form a graph across apps through each migration's dependencies list, and migrate applies them in dependency order.

You add the rules. Each app owns the writes to its own tables. Apps import each other only downward through the layers. Other apps reach an app's data only through its public module, such as services.py.

A typical request shows both layers at work:

  1. A view in a workflow app such as orders handles the HTTP request.
  2. The view calls orders.services.place_order(). That function writes Order rows inside a transaction.
  3. When it needs data from a lower app, place_order() calls that app's public functions, such as accounts.services.get_customer(). It never queries accounts.models directly.
  4. Effects in apps that orders must not import, such as creating an invoice in billing, run through a hook. The hook is defined in the lower app, connected in the higher app's ready(), and fired from transaction.on_commit.
  5. A CI check fails the build if any import breaks the layer order.

Django enforces none of the ownership or layering rules itself. The structure holds because of steps 3 to 5, and the following sections cover each of them.

Who should use a domain app structure?

This structure suits teams whose main problem is coupling, not lines of code. It fits best when one or more of the following is true:

  • Several teams or many developers work in one Django codebase. Ownership by app gives each team a clear area to change, and the dependency rule tells them who is affected.
  • A single models.py or app has grown to the point where unrelated changes collide. Common signs are merge conflicts in the same files and parallel migrations that need makemigrations --merge.
  • Changes in one area keep breaking another. A layered graph limits which code a change can reach.
  • The business domains are stable. Billing, inventory and accounts are unlikely to merge or split next quarter.
  • You may want to extract a service later. Clean seams in the monolith are a prerequisite, though not a guarantee, as the final section explains.

It is a poor fit for a small team with one domain or a schema that is still changing quickly. There, the facades, service modules and migration work cost more than the coupling they prevent. The last section covers that case and the alternatives in more detail.

Why do Django apps need a one-directional dependency rule?

A boundary only helps if dependencies across it point one way. Without that rule, every app can import every other, and the split adds folders without adding structure.

Write the rule down in the repository, next to the code, as an ordered list of layers. An app may import from its own layer or any layer below it, never from above:

  1. Foundation: accounts, core
  2. Domain: catalog, billing
  3. Workflow: orders, fulfilment

Drawn as a directed graph, the edges run downward: orders → billing → accounts, orders → catalog → accounts. billing can call into accounts to look up a customer. accounts never imports billing, even to show a balance on a profile page. That view belongs in a higher layer that reads from both.

Any cycle in this graph is a design bug, not an import-ordering problem. Moving an import inside a function can silence the error at load time, but the two apps still cannot be understood, tested or extracted separately. A cycle usually means a concept sits in the wrong app, or two apps are really one.

Migrations follow the same layering. A billing migration may depend on an accounts migration. The reverse dependency recreates the cycle in the migration graph, where it is harder to remove than in the code.

The rule pays off most when several teams share one codebase, or when changes in one area keep breaking another. A one-directional graph limits what a change can affect. Editing orders cannot break accounts, so the owners of foundational apps can change them knowing exactly which apps depend on them.

 LAYER 3         +----------+               +------------+
 Workflow        |  orders  |               | fulfilment |
                 +----------+               +------------+
                   |      |
              +----+      +---------+
              |                     |
              v                     v
 LAYER 2 +----------+          +----------+
 Domain  | billing  |          | catalog  |
         +----------+          +----------+
           |      ^                 |
           |      |                 |
           |      X  forbidden:     |
           |      |  accounts ->    |
           |      |  billing        |
           v      |                 v
 LAYER 1 +------------------------------+   +----------+
 Found.  |           accounts           |   |   core   |
         +------------------------------+   +----------+

 Rule: an app imports from its own layer or below, never above.
       Migration dependencies follow the same direction:
       a billing migration may depend on an accounts migration.
 Any upward edge closes a cycle: a design bug, not an import-order bug.

Layered dependency graph in which imports and migration dependencies point only downward, from workflow apps through domain apps to foundation apps, so an edge from accounts up to billing would close a cycle and is forbidden.

How do you fix circular imports in Django?

Python raises a circular import when two modules need each other while still loading. Django adds its own triggers. When the app registry populates, it imports every installed app's models module in order. If orders/models.py imports accounts.models for a ForeignKey and accounts imports orders for a reverse helper, one module sees the other only partially loaded. A service that imports a view to reuse a form or serializer creates the same problem one layer up. Code that runs at module level, such as queries or model imports in an AppConfig module, can fail with AppRegistryNotReady because the registry is not populated yet.

Fix When it fits Cost
String reference 'accounts.Customer' in a relation Model-to-model foreign keys The type checker and IDE lose the direct link
apps.get_model('accounts', 'Customer') inside a function Occasional lookups, migrations The dependency still exists but is hidden at runtime
Move shared enums or dataclasses into a lower core app Both apps need the same types You need an extra app and must keep it free of domain logic
Signal or callback registry, registered in ready() A lower app must notify higher apps it can't know about Control flow becomes indirect

Signals remove the import but keep the coupling. Receivers are not visible at the call site. They run synchronously inside the sender's transaction, and an exception in a receiver propagates back to the sender. Use a signal only when the dependency direction forbids a direct call. If the caller needs a result or a guaranteed order, an explicit service call in the permitted direction is clearer.

Side effects in another domain, such as emails, events or cache invalidation, belong in transaction.on_commit. That way a rolled-back order never announces itself.

from django.db import models, transaction
from django.dispatch import Signal

order_placed = Signal()  # receivers get sender and order


class Order(models.Model):
    # String reference: no module-level import of accounts.models, so no cycle at app loading.
    customer = models.ForeignKey("accounts.Customer", on_delete=models.PROTECT)
    total_cents = models.PositiveIntegerField()


def place_order(customer, total_cents):
    with transaction.atomic():
        order = Order.objects.create(customer=customer, total_cents=total_cents)
        # Cross-domain side effects run only after the commit succeeds,
        # so a rollback never produces an email for an order that does not exist.
        transaction.on_commit(lambda: order_placed.send(sender=Order, order=order))
    return order


from django.apps import AppConfig, apps


class BillingConfig(AppConfig):
    name = "billing"

    def ready(self):
        # The registry is populated here, so imports and get_model are safe.
        from orders.models import order_placed
        order_placed.connect(self.on_order_placed, dispatch_uid="billing_order_placed")

    @staticmethod
    def on_order_placed(sender, order, **kwargs):
        # Late lookup avoids importing billing.models at module import time.
        Invoice = apps.get_model("billing", "Invoice")
        Invoice.objects.create(order_id=order.pk, amount_cents=order.total_cents)

A string foreign key reference, a signal defined in the lower orders app and connected in billing's ready(), apps.get_model for a late lookup, and transaction.on_commit so the cross-domain receiver runs only after the order commits.

How should Django apps expose a public interface to each other?

Give each domain app one module that other apps are allowed to import, such as services.py or api.py, and treat everything else in the app as private. Writes go through service functions like place_order() or cancel_subscription(). Reads go through query functions like get_active_plan_for_user() that return model instances, dataclasses or plain values. The billing app should not reach into orders.models and filter on order__customer__plan__tier. Each chained lookup across an app boundary ties billing to the other app's field names and relationships.

Python does not enforce any of this. Nothing stops an import of orders.models, and Django's ORM will happily follow a foreign key into another app. The boundary exists only through convention, code review and the automated checks covered in the next section.

A strict ban on cross-app joins works against what the ORM does well. If every cross-domain read must go through a service call, a list view can end up calling a query function per row, which produces N+1 queries. Other teams then copy filtering logic into their own apps to avoid the round trips. For hot read paths, such as reporting, admin list views and dashboards, allow an explicit exception. Use select_related or a join across apps, keep it in one named module, and document why it exists.

The payoff is a smaller blast radius. When orders changes a model field, only its own code and its public functions can break. Reviewers check that the interface's signatures and behaviour still hold. They do not need to search the codebase for every query that touches the table.

from dataclasses import dataclass

from django.db import transaction

from .models import Order  # models stay private to this app


@dataclass(frozen=True)
class OrderSummary:
    id: int
    customer_id: int
    total_cents: int


def place_order(customer_id: int, total_cents: int) -> OrderSummary:
    # Write path: callers never touch Order.objects directly.
    with transaction.atomic():
        order = Order.objects.create(customer_id=customer_id, total_cents=total_cents)
    return OrderSummary(order.id, order.customer_id, order.total_cents)


def get_open_orders_for_customers(customer_ids: list[int]) -> list[OrderSummary]:
    # Read path takes a batch of IDs so list views make one query, not one per row.
    rows = Order.objects.filter(customer_id__in=customer_ids, status="open")
    return [OrderSummary(o.id, o.customer_id, o.total_cents) for o in rows]


from orders.models import Order


def revenue_rows_by_plan_tier():
    return (
        Order.objects.select_related("customer__plan")
        .filter(status="paid")
        .values("customer__plan__tier", "total_cents")
    )

Other apps call the public functions in orders/services.py, which return dataclasses and accept batches of IDs. One cross-app join is allowed for a reporting hot path, and it lives in a single named, documented module.

How do you move models between Django apps without losing data?

The documented approach leaves the table where it is and moves only Django's migration state. First, set Meta.db_table on the model to its current table name, for example billing_invoice, so the name no longer depends on the app label. Then write two migrations wrapped in SeparateDatabaseAndState. The old app gets a DeleteModel in state_operations. The new app gets a CreateModel in state_operations, with the same db_table and no database operations. Make the new app's migration depend on the old one, so the model never exists in both apps' state at once.

The table survives, but some rows elsewhere depend on the app label:

  • ContentType rows are keyed on app_label and model. If you do nothing, post_migrate creates a new row for the new app. The old row is left stale.
  • Permissions are attached to that old row. Group and user grants then point at permissions the code no longer checks.
  • Generic foreign keys store content_type_id, so they keep referencing the stale row.

The fix is a data migration that updates the existing ContentType's app_label before post_migrate runs. This keeps permissions and generic relations intact. A swappable model such as AUTH_USER_MODEL is much harder to move. Leave it where it is unless you have no other option.

Keep migration dependencies consistent with your layering. For apps with long histories, squash or reset before the move so fewer historical migrations reference the old label. Ship the move as its own deploy, with no schema changes. If it breaks, you know the cause.

These mistakes often only show up against real data, such as orphaned permissions or generic relations. Rehearse the move on a copy of production first.

How can you enforce app boundaries automatically in CI?

Boundaries enforced only by convention erode under deadline pressure. One "temporary" cross-app model import gets copied, and within a few months the dependency rule lives only in a wiki page. A mechanical check moves the rule into code review, where violations surface while they are still cheap to fix. There are three practical options.

Allowed-dependency test. Keep a map of which apps each app may depend on, then write a test that inspects each app's modules and fails when an import falls outside that map. It runs in your existing test suite and needs no new tooling.

Import-linting tool. Dedicated import linters let you declare layers or forbidden dependencies in a config file. They analyse the whole import graph, including indirect dependencies where app A reaches app C through app B.

Grep or AST check. A grep for from billing.models import outside billing/ takes minutes to set up. An AST-based script, like the example below, walks ImportFrom nodes instead of matching text, so it also catches multi-line and aliased imports that grep misses.

Option Setup effort Precision Maintenance
Allowed-dependency test Medium Direct imports only Update the map as apps change
Import-linting tool Medium Includes indirect imports Keep the contract config current
Grep / AST check Low Only the patterns you list Add patterns by hand

Start in warn-only mode. Record the existing violations as a baseline, fail the build only on new ones, and shrink the baseline over time. Expect some CI friction and ongoing allow-list upkeep. Give every exception an owner and a reason, or the allow-list will become the new convention.

How can domain apps save engineering time?

The savings come from shrinking the area an engineer has to think about, review, test and coordinate on. They appear in several places:

  • Smaller review scope. When other apps can only reach billing through billing/services.py, a change to a private billing model needs review against that interface. Reviewers do not need to search the whole codebase for queries that touch the table.
  • Targeted test runs. Tests that live inside each app can run on their own while you iterate, for example python manage.py test apps.billing. The layering also tells you which other suites a change can affect: those of billing and of the apps above it. You still need the full suite in CI. The difference is that the local feedback loop is short.
  • Fewer migration and merge conflicts. When all models share one app, two branches that each add a migration produce conflicting leaf nodes, and someone has to run makemigrations --merge or renumber. With separate apps, teams working in different domains create migrations in separate directories and rarely collide.
  • Faster onboarding. A new engineer can learn one app and its public module, plus the layer list. They do not need a mental model of every relationship in the schema.
  • Cheaper debugging. In a one-directional graph, a regression in accounts cannot come from code in orders. That rules out half the candidates before you open a debugger.
  • Lower cost for later extraction. If you ever do move a domain into its own service, much of the work of finding the seams is already done.

Illustrative estimate, using assumed inputs only. Assume 20 engineers share one app that holds all the models. Assume they hit 12 migration or merge conflicts a month, and each takes 30 minutes to resolve and re-test. That is 6 engineer-hours a month. Assume domain apps cut those conflicts to 3 a month, saving about 4.5 hours. Now assume each engineer runs the local test suite 10 times a day. Cutting a local run from an assumed 8 minutes for the full suite to 2 minutes for one app saves an hour of waiting per engineer per day. Set this against the assumed costs: the initial split, writing facades and service modules, and maintaining CI allow-lists. Your actual numbers depend on team size, test-suite shape and how well the boundaries match how work really divides. Measure your own conflict rate and test times before and after.

The savings only appear if boundaries are enforced. Without the CI check, cross-app imports creep back, review scope grows again, and you keep the overhead of the split without the benefit.

When should you avoid splitting a Django monolith, and what are the alternatives?

If you do split, do it incrementally. Draw the current import graph first, then extract leaf domains: the ones nothing else imports, such as notifications or audit logging. Moving them changes no other code, so a wrong call costs little. Put a facade at each old import path that re-exports the new location and emits a DeprecationWarning, so callers can migrate on their own schedule. Move tests with the code so each app's suite runs on its own. Stop once the boundaries stop causing pain. A half-split monolith with clean seams is a valid end state.

The development cost is real. For a small team, facades and service modules can stay boilerplate that never pays off. Domains drawn wrong early are expensive to reverse, because model moves need migrations, not just refactors. Boundaries that follow today's org chart may not survive a reorganisation. Modular Django also does not make extracting services easy later. Shared transactions and cross-app foreign keys still couple apps at the data layer.

Approach Fits when Main cost
One well-organised app Small team, one domain, schema still changing Gets crowded as the codebase grows
Packages inside one app Clear subdomains but one shared schema Boundaries depend on convention only
Full domain apps Several teams, stable domains, CI enforcement Indirection and migration overhead
Separate services Independent scaling or deployment, data already separable Distributed transactions, network failure, operations burden

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.
  • 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.