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

# ModelState, instantiation, and from_db

How does a model instance know whether it came from the database or was constructed in memory, and why does `Model.from_db` skip default field computations?

Every model instance carries two dictionaries of truth: its ordinary `"instance.__dict__"` (holding column values like `"id"`, `"headline"`, `"desk_id"`) and a tiny companion object at `"instance._state"`, an instance of **`ModelState`** (`django/db/models/base.py:ModelState`).

## Inside `django.db.models.base.ModelState`: lazy descriptors to save per-row memory

Open `django/db/models/base.py` lines 462–499:

```python
class ModelStateFieldsCacheDescriptor:
    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        res = instance.fields_cache = {}
        return res

class ModelStateFetchModeDescriptor:
    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        res = instance.fetch_mode = FETCH_ONE
        return res

class ModelState:
    db = None
    adding = True
    fields_cache = ModelStateFieldsCacheDescriptor()
    fetch_mode = ModelStateFetchModeDescriptor()
    peers = ()
```

Look at how carefully `ModelState` avoids per-row allocations when a queryset materializes ten thousand rows!
- On a freshly constructed `ModelState()`, its instance dictionary (`"__dict__"`) starts **completely empty**: `db` (`None`), `adding` (`True`), and `peers` (`()`) are inherited as class attributes without allocating instance keys.
- Even `fields_cache` and `fetch_mode` are **lazy descriptors**! Django does not allocate a `{}` dictionary for `fields_cache` on a single instance until some relation is actually cached or inspected.
- In Django `6.1`, `ModelState` gained `fetch_mode` and `peers` (a tuple of `weakref.ref` handles to sibling rows fetched in the same `FETCH_PEERS` queryset). Look at `ModelState.__getstate__` (lines 491–495): it explicitly pops `"peers"` before pickling because weak references cannot be serialized!

## `Model.__init__` vs. `Model.from_db` and the `DEFERRED` sentinel

Now open **`Model.__init__`** (`django/db/models/base.py:Model.__init__`) and **`Model.from_db`** (`django/db/models/base.py:Model.from_db`).

Read lines 524–545 of `Model.__init__` carefully. Django maintains **two completely separate initialization loops** inside `__init__`:

1. **The positional fast path (`if not kwargs:`, lines 524–533):** Zips positional `args` straight across `Options.concrete_fields` (`django/db/models/options.py:Options`) and calls `setattr(self, field.attname, val)` — skipping every entry equal to **`DEFERRED`** (`django/db/models/base.py:DEFERRED`), a module-level sentinel object! Because every concrete field receives either its SQL value or `DEFERRED`, the trailing `for field in fields_iter:` loop never executes a single iteration and `Field.get_default` (`django/db/models/fields/__init__.py:Field.get_default`) is never called.
2. **The keyword path (`else:`, lines 534–613):** Walks `Options.fields`, checks for duplicate positional+keyword arguments, pops both `Field.name` (related instances) and `Field.attname` (`"_id"` integers) from `kwargs`, calls `Field.get_default` for every omitted concrete field, and validates leftover keys against `_property_names` and virtual fields before raising `TypeError` on unexpected keywords.

Now look at **`Model.from_db`** (lines 617–630), the classmethod `ModelIterable` calls for every row coming off a database cursor:

```python
@classmethod
def from_db(cls, db, field_names, values, *, fetch_mode=None):
    if len(values) != len(cls._meta.concrete_fields):
        values_iter = iter(values)
        values = [
            next(values_iter) if f.attname in field_names else DEFERRED
            for f in cls._meta.concrete_fields
        ]
    new = cls(*values)
    new._state.adding = False
    new._state.db = db
    if fetch_mode is not None:
        new._state.fetch_mode = fetch_mode
    return new
```

That design delivers two massive wins simultaneously:
- **Zero wasted default computations on `QuerySet.defer` / `QuerySet.only` rows:** If a model declares `token = CharField(default=generate_expensive_uuid)` and a query defers `"token"`, `Model.from_db` places `DEFERRED` into that positional slot so `Model.__init__` skips the slot without invoking the default callable.
- **Nearly 2× faster row hydration:** Calling `cls(*values)` hits the positional fast path instead of dictionary popping and default resolution.

Measure both effects — and the hidden cost of a single `post_init` (`django/db/models/signals.py:post_init`) signal receiver — live on Django `6.1.3`:

```text recording=ch06-bench
Model instantiation cost on Story (50,000 calls x 5 trials, microseconds)
  path                                         us_per_call   relative
  Story(*values) [positional fast path]               5.63      0.94x
  Story.from_db(...) [ModelIterable path]             5.99      1.00x
  Story(**kwargs) [keyword instantiation]            11.28      1.88x
  Story.from_db(...) + 1 post_init receiver           7.31      1.22x
  Story(**kwargs) + 1 post_init receiver             12.78      2.13x
```

At `5.99 us` per row vs `11.28 us` (`1.88x`), `Model.from_db`'s positional fast path cuts pure-Python instantiation time nearly in half! And notice line 8: **connecting even one empty `post_init` receiver adds `+1.32 us` (`+22%`) to every single model row hydrated from the database** — because `Model.__init__` fires both `pre_init` (line 511) and `post_init` (line 615) on every instance!

## Identity, equality, and why unsaved models are unhashable

Look at `Model.__eq__` (`django/db/models/base.py:Model.__eq__`) and `Model.__hash__` (`django/db/models/base.py:Model.__hash__`):

1. Two model instances compare equal if and only if they share the exact same **`Options.concrete_model`** (`django/db/models/options.py:Options`) and the same non-null primary key (`my_pk == other.pk`). That means a `"PublishedStory"` proxy instance with `pk=1` compares **`True`** against a `"Story"` instance with `pk=1` — even though their Python classes differ! Two unsaved instances (`pk is None`) compare equal only by object identity (`self is other`).
2. `Model.__hash__` hashes `Model.pk` — and **raises `TypeError` whenever `_is_pk_set()` is `False`**! Why? Because Python requires an object's hash never to change while it lives inside a `set` or `dict`. If an unsaved `"Story()"` were hashable before `save()` assigned its database `id`, saving it would mutate its hash and silently break every `set` or `dict` holding it.

Verify all three properties — `adding`/`db`, `hash(unsaved)`, `from_db` skipping callable defaults, and proxy equality — live in `ch06-models`:

```text recording=ch06-models
ModelState, Model.__init__ vs Model.from_db, and identity
  unsaved Story(): adding=True db=None pk=None
  hash(unsaved) -> TypeError: Model instances without primary key value are unhashable
  callable default invocations: Model()=1, Model.from_db(deferred)=0
  PublishedStory(pk=1) == Story(pk=1): True (concrete_model matches)
```

## Where `django.db.models.base.ModelState` and instantiation leak

- **Attaching `pre_init` or `post_init` signals to high-volume models silently taxes every queryset.** Even a no-op `post_init` listener slows `Model.from_db` by `+22%` on every row returned by `"SELECT"` queries. Override `Model.from_db` directly if you need to snapshot field values on load, or compute lazily on access.
- **Putting a model instance with an explicit/auto PK into a `set` before cloning it (`obj.pk = None; obj._state.adding = True`).** Remember how Django recommends copying a row: setting **both** `obj.pk = None` *and* `obj._state.adding = True`! If you forget `_state.adding = True` on a model whose PK has a default (like `django.db.models.UUIDField`), `Model.save` behaves differently — which brings us directly to how `save()` decides between `"INSERT"` and `"UPDATE"`.
- **Two Python instances of the same database row do NOT share state.** Unlike SQLAlchemy's identity map, Django has no session-wide object cache: calling `"Story.objects.get(pk=1)"` twice returns two distinct Python objects (`s1 == s2` is `True`, `s1 is s2` is `False`), and mutating `"s1.headline"` does not update `"s2.headline"`.

Now that we know how a model tracks `adding`, `db`, and deferred columns inside `_state`, let's trace what happens when you persist that instance back to SQL in [Inside Model.save: insert vs. update](saving.md).
