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

# What ModelBase.__new__ builds at import time

What actually happens to a model class dictionary when Python executes a `Model` subclass definition?

When Python finishes running the indented body of our newsroom's `"Story"` model, it hands `(name, bases, attrs)` to **`ModelBase`** (`django/db/models/base.py:ModelBase`) — the metaclass of `Model`. By the time `ModelBase.__new__` returns, almost nothing you assigned in the class body still exists in `"Story.__dict__"` in the form you wrote it.

## Dissecting `ModelBase.__new__` step by step

Open `ModelBase.__new__` (`django/db/models/base.py:ModelBase.__new__`). Its first guard (lines 103–105) checks `parents = [b for b in bases if isinstance(b, ModelBase)]`; if `parents` is empty, it is creating `Model` itself and delegates directly to `type.__new__`. For every real model subclass, `ModelBase.__new__` executes seven distinct stages:

1. **Split normal attributes from contributables (lines 108–123):** `ModelBase.__new__` pops `"__module__"`, `"__classcell__"`, and `"Meta"` out of `attrs`, then loops over the remaining class attributes calling `_has_contribute_to_class` (`django/db/models/base.py:_has_contribute_to_class`, line 90: `not inspect.isclass(value) and hasattr(value, "contribute_to_class")`). Ordinary methods, properties, and nested classes (such as `"Story.Status"`, a `TextChoices` enum class!) go straight to `type.__new__` so Python runs `__set_name__` normally. Every `Field` (`django/db/models/fields/__init__.py:Field`) and `Manager` (`django/db/models/manager.py:Manager`) instance is held aside in `"contributable_attrs"` — it is **never** stored raw in `"Story.__dict__"`.
2. **Locate the owning `AppConfig` and build `Options` (lines 125–146):** Using `Apps.get_containing_app_config` (`django/apps/registry.py:Apps.get_containing_app_config`), Django derives `app_label` (raising `RuntimeError` if a non-abstract model sits outside `INSTALLED_APPS` without an explicit `"Meta.app_label"`). It then calls `ModelBase.add_to_class` (`django/db/models/base.py:ModelBase.add_to_class`) with `"_meta"` and `Options(meta, app_label)` (`django/db/models/options.py:Options`), which attaches `Options` onto `"_meta"` and deletes the `"Meta"` reference.
3. **Synthesize three per-model exception classes (lines 147–192):** For every concrete and proxy model, `subclass_exception` (`django/db/models/base.py:subclass_exception`) dynamically creates three pickleable exception subclasses attached directly to the model class:
   - `"DoesNotExist"` subclassing `ObjectDoesNotExist` (`django/core/exceptions.py:ObjectDoesNotExist`) — or the parent model's `"DoesNotExist"` on concrete inheritance.
   - `"MultipleObjectsReturned"` subclassing `MultipleObjectsReturned` (`django/core/exceptions.py:MultipleObjectsReturned`).
   - **Django `6.1`'s `"NotUpdated"`** subclassing both `ObjectNotUpdated` (`django/core/exceptions.py:ObjectNotUpdated`) and `DatabaseError` (`django/db/utils.py:DatabaseError`) so `force_update=True` or `update_fields=...` failures can be caught per model while preserving backwards compatibility with `except DatabaseError`.
4. **Run **`contribute_to_class`** on every field and manager (lines 213–214):** `ModelBase.add_to_class` dispatches `contribute_to_class` on each contributable object. This is the central protocol of Django's ORM:
   - A scalar field (`Field.contribute_to_class`, `django/db/models/fields/__init__.py:Field.contribute_to_class`) registers itself inside `Options.add_field`, installs `DeferredAttribute(self)` on the class at its `attname`, and — whenever `choices` is set — attaches `"get_<name>_display"` as a `functools.partialmethod` bound to `Model._get_FIELD_display`.
   - A `ForeignKey` (`django/db/models/fields/related.py:ForeignKey`) installs **three** descriptors across **two** classes: `ForeignKeyDeferredAttribute` on `"desk_id"`, `ForwardManyToOneDescriptor` on `"desk"`, and (lazily once the target model is loaded) `ReverseManyToOneDescriptor` on `"Desk.stories"`!
   - A `ManyToManyField` (`django/db/models/fields/related.py:ManyToManyField`) installs `ManyToManyDescriptor` on both sides.
   - A `Manager` (`django/db/models/manager.py:BaseManager.contribute_to_class`) installs `ManagerDescriptor` so accessing `"Story.objects"` works on the class while accessing `"story.objects"` on an instance raises `AttributeError`.
5. **Resolve inheritance (lines 224–378):** Proxies link to their `concrete_model`; concrete subclasses synthesize `"<parent>_ptr"` `OneToOneField` parent links; abstract base fields are `copy.deepcopy`-cloned onto the concrete child. (We trace all three in Section 6.7.)
6. **Finalize in `ModelBase._prepare` (lines 388, 398–451):** Abstract models return early at line 386 (resetting `attr_meta.abstract = False` so subclasses are concrete unless they opt back in!). Concrete and proxy models run `ModelBase._prepare` (`django/db/models/base.py:ModelBase._prepare`):
   - `Options._prepare` (`django/db/models/options.py:Options._prepare`) checks whether a primary key was declared; if not, it reads `AppConfig.default_auto_field` (falling back to `DEFAULT_AUTO_FIELD`, `BigAutoField` in our newsroom project) and synthesizes `"id"` with `auto_created=True`.
   - If the class has no docstring, lines 422–426 auto-generate `"Story(id, headline, ...)"` from its field names.
   - If no manager was declared, lines 434–442 attach a default auto-created `Manager` at `"objects"` (unless a field is already named `"objects"`, which raises `ValueError`).
   - Unnamed `"Meta.indexes"` receive deterministic names via `set_name_with_model`, and `class_prepared` (`django/db/models/signals.py:class_prepared`) fires.
7. **Register in the app registry (line 389):** `Apps.register_model` (`django/apps/registry.py:Apps.register_model`) stores the class in `all_models[app_label][model_name]` and flushes any pending `lazy_related_operation` callbacks waiting on string foreign keys like `"StoryBeat"`.

## Watching the transformation live on our newsroom model

Inspect `"Story.__dict__"` and `"Desk.__dict__"` right after Django `6.1.3` boots our newsroom app:

```text recording=ch06-models
ModelBase.__new__: what Story.__dict__ actually contains at runtime
  'Meta' in Story.__dict__: False
  Story.__dict__['id'                ] -> DeferredAttribute
  Story.__dict__['headline'          ] -> DeferredAttribute
  Story.__dict__['desk_id'           ] -> ForeignKeyDeferredAttribute
  Story.__dict__['desk'              ] -> ForwardManyToOneDescriptor
  Story.__dict__['beats'             ] -> ManyToManyDescriptor
  Story.__dict__['objects'           ] -> ManagerDescriptor
  Story.__dict__['get_status_display'] -> partialmethod
  Desk.__dict__['stories']             -> ReverseManyToOneDescriptor
  synthesized exceptions: DoesNotExist(ObjectDoesNotExist), MultipleObjectsReturned(MultipleObjectsReturned), NotUpdated(ObjectNotUpdated, DatabaseError)
  auto-generated __doc__: 'Story(id, headline, slug, body, priority, status, published_at, desk, reporter, edition)'
```

Every single piece of that trace confirms the metaclass rewrite: `"Meta"` is gone, every field has vanished behind a descriptor, one `"ForeignKey"` turned into `"desk_id"` + `"desk"` + `"Desk.stories"`, `"status"` grew `"get_status_display"`, three per-model exception subclasses appeared, and even `"Story.__doc__"` was synthesized for you.

## Where the metaclass leaks

- **Importing a model module before `django.setup()` or outside `INSTALLED_APPS` crashes immediately.** Because `ModelBase.__new__` runs at Python class-definition time (inside `import`) and calls `Apps.get_containing_app_config`, importing a model before `INSTALLED_APPS` is loaded — or placing a concrete model in a module whose app is missing from `INSTALLED_APPS` — raises `RuntimeError` immediately.
- **Replacing a field attribute after class creation bypasses `contribute_to_class`.** Writing `"Story.extra = CharField(...)"` after the `class` block merely drops a bare `django.db.models.CharField` object onto `"Story.__dict__"`; `"_meta"` never learns about it and queries will ignore it. Dynamic fields must go through `ModelBase.add_to_class` (or be declared in the class body).
- **Custom objects with a `contribute_to_class` method get intercepted.** Because `_has_contribute_to_class` checks only `not inspect.isclass(value) and hasattr(value, "contribute_to_class")`, any third-party descriptor instance defining that method name is invoked by `ModelBase` rather than assigned normally.

Every field stripped from the class body now lives inside `"_meta"`. Next, we open `django.db.models.options.Options` and see how fields translate between Python values, SQL column types, and migration blueprints in [Options, fields, and column metadata](options-and-fields.md).
