---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Why import order breaks startup

What triggers `AppRegistryNotReady`, and how does Django defer cross-app model references until every model class exists?

Sooner or later every Django project greets a developer with `AppRegistryNotReady: Apps aren't loaded yet.` — usually after an agent or engineer adds an innocent model import to an app's `__init__.py`, puts a helper import at the top of `apps.py`, or runs a quick standalone script without booting Django first. Tracing the exact line that throws the exception turns every startup traceback into a five-second diagnosis.

## The guard inside `ModelBase.__new__`

When Python executes a `class` block inheriting from `Model`, `ModelBase.__new__` must discover which installed application owns the class so it can assign `Options.app_label` (`django/db/models/base.py:ModelBase.__new__`). On line 132 it calls `Apps.get_containing_app_config` with the model's `__module__` string (`django/apps/registry.py:Apps.get_containing_app_config`). The very first line of `get_containing_app_config` calls `Apps.check_apps_ready` (`django/apps/registry.py:Apps.check_apps_ready`).

Watch what happens when two clean Python subprocesses both run `import newsroom.models` without calling `django.setup()` — one with `"DJANGO_SETTINGS_MODULE"` set in its environment, and one without:

```text recording=ch02-startup
Controlled startup failures before and during django.setup()
  TRAP import newsroom.models (with DJANGO_SETTINGS_MODULE) -> AppRegistryNotReady: Apps aren't loaded yet.
  TRAP import newsroom.models (without DJANGO_SETTINGS_MODULE) -> ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
```

Two identical imports, two different exception types. Why?

> **Why.** Open `Apps.check_apps_ready` (`django/apps/registry.py:Apps.check_apps_ready`). When `Apps.apps_ready` is `False`, Django deliberately reads `settings.INSTALLED_APPS` *one line before* raising `AppRegistryNotReady`. If the developer forgot to configure settings at all, touching `settings.INSTALLED_APPS` wakes `LazySettings._setup` and surfaces the much more actionable `ImproperlyConfigured` error instead of blaming the app registry.

That single guard accounts for almost every startup crash in the wild. In a standalone script that sets `"DJANGO_SETTINGS_MODULE"` and skips `django.setup()`, `ModelBase.__new__` hits `check_apps_ready` while `Apps.apps_ready` is still `False`. Inside an app's `__init__.py` or `apps.py`, Phase 1 (`AppConfig.create`) imports the package while `Apps.apps_ready` is still `False`, so any top-level model import inside either file crashes before Phase 1 can finish.

Phase 2 has its own matching guard: `Apps.check_models_ready` (`django/apps/registry.py:Apps.check_models_ready`). Calling `Apps.get_model` during Phase 2 fails with `AppRegistryNotReady("Models aren't loaded yet.")` because `require_ready=True` is the default (`django/apps/registry.py:Apps.get_model`). Internal ORM code that needs to inspect already-imported models mid-Phase 2 bypasses that barrier via `Apps.get_registered_model`, which looks straight into `Apps.all_models` without waiting for `Apps.models_ready` (`django/apps/registry.py:Apps.get_registered_model`).

> **Trap.** Putting both a project root and its parent directory on `sys.path` can let Python import the same file under two module paths — for example `"newsroom.models"` and `"desk.newsroom.models"`. Python executes the file twice, creating two distinct classes for the same `(app_label, model_name)` key. `Apps.register_model` catches the collision immediately and raises `RuntimeError("Conflicting ... models")`, or emits a `RuntimeWarning` if the identical module path is forcibly reloaded (`django/apps/registry.py:Apps.register_model`).

## Breaking cross-app cycles with `lazy_model_operation`

If Phase 2 imports each app's models module one after another, how does a model in our Subscribers app declare `ForeignKey("newsroom.Desk", ...)` when Subscribers appears *before* Newsroom in `INSTALLED_APPS` — or when two apps point foreign keys at each other in a cycle?

String model references are never resolved eagerly when a `ForeignKey` is instantiated. Instead, `RelatedField` hands a resolution callback to `lazy_related_operation`, which normalizes string targets (`"self"`, `"Desk"`, `"newsroom.Desk"`) into `(app_label, model_name)` tuples and delegates to `Apps.lazy_model_operation` (`django/db/models/fields/related.py:lazy_related_operation`, `django/apps/registry.py:Apps.lazy_model_operation`).

`Apps.lazy_model_operation` is a remarkably compact piece of recursive currying built on `functools.partial`. Given a callback expecting `n` model classes and `n` `(app_label, model_name)` keys, it peels off the first key and asks `Apps.get_registered_model` whether that model is already in `Apps.all_models`:

- If the model is already registered, Django partially applies that class to the callback with `functools.partial` and recurses immediately on the remaining keys. Once no keys remain, the fully bound callback executes on the spot.
- If the model has not been imported yet, Django appends a small continuation closure to `self._pending_operations[(app_label, model_name)]` and returns — letting Phase 2 keep moving without blocking or importing out of order.

Later, at the very end of `Apps.register_model`, Django calls `Apps.do_pending_operations(model)`, which pops `self._pending_operations[(app_label, model_name)]` and calls every waiting continuation with the newly registered class (`django/apps/registry.py:Apps.do_pending_operations`). Each continuation binds that class via `functools.partial` and either fires immediately or queues itself on the next missing key.

Reordering `INSTALLED_APPS` in a fresh subprocess so Subscribers loads *before* Newsroom proves the queue in motion:

```text recording=ch02-startup
Cross-app lazy_model_operation: subscribers before newsroom
  queue lazy_model_operation keys=(('subscribers', 'subscription'), ('newsroom', 'desk'))
  do_pending_operations(('subscribers', 'subscription')) running 1 queued callback(s)
  do_pending_operations(('newsroom', 'desk')) running 1 queued callback(s)
  do_pending_operations(('newsroom', 'reporter')) running 2 queued callback(s)
  do_pending_operations(('newsroom', 'story')) running 5 queued callback(s)
  do_pending_operations(('newsroom', 'storybeat')) running 3 queued callback(s)
  do_pending_operations(('newsroom', 'correction')) running 1 queued callback(s)
  resolved Subscription.desk.remote_field.model -> Desk
  remaining _pending_operations -> 0
```

Look closely at the first three lines of that trace. When Subscribers defines its subscription model, neither model is registered yet, so the callback waits on `("subscribers", "subscription")`. A millisecond later that model finishes registering, fires `do_pending_operations(("subscribers", "subscription"))`, binds the subscription class, sees `("newsroom", "desk")` is still absent, and re-queues on `("newsroom", "desk")`. When Newsroom finally imports and registers its desk model, `do_pending_operations(("newsroom", "desk"))` fires that continuation, wiring the foreign key (`remote_field.model -> Desk`) and attaching the reverse `"subscriptions"` descriptor cleanly — leaving `0` pending operations when boot finishes.

Even within a single file, notice how the same mechanism resolves forward references: Story declares `ManyToManyField` through StoryBeat before StoryBeat is defined two classes lower in the file, so Story queues `5` callbacks that drain automatically once StoryBeat registers.

With Phases 1 and 2 clear, let's look at everything `django.setup` runs *before* and *after* `Apps.populate` — including the single import line that ate `40%` of our startup budget and why touching the database inside `AppConfig.ready` breaks migrations and tests.
