Django 6.1.3

2.3 Booting Django

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. On line 132 it calls Apps.get_containing_app_config with the model’s __module__ string. The very first line of get_containing_app_config calls 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:

Recorded on Django 6.1.3 ch02-startup script
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?

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. Calling Apps.get_model during Phase 2 fails with AppRegistryNotReady("Models aren't loaded yet.") because require_ready=True is the default. 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.

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.

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:

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

Recorded on Django 6.1.3 ch02-startup script
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.