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

# Options, fields, and column metadata

What lives inside `Model._meta`, and how does a model field bridge Python types, database column types, and validation rules?

Once `ModelBase.__new__` finishes, every piece of structural knowledge Django has about a model — its table name, primary key, forward columns, many-to-many bridges, reverse relations, indexes, constraints, and managers — sits inside **`Options`** (`django/db/models/options.py:Options`), attached to the model as `"_meta"`.

## Inside `django.db.models.options.Options` (`_meta`): cached lists and the two-tier field map

Open `django/db/models/options.py:Options` lines 90–170 and 531–696. `Options` stores only three raw mutable buckets during class construction — `local_fields`, `local_many_to_many`, and `private_fields` (inserted in declaration order via `bisect.insort` using each field's monotonic `creation_counter`, lines 340–351).

Everything the ORM reads at runtime is exposed as `@cached_property` attributes wrapped in `ImmutableList` (`django/utils/datastructures.py:ImmutableList`):

- **`concrete_fields`**: every **concrete field** (`field.concrete is True`, meaning `field.column is not None` — a real column in SQL) across the model and its concrete parents. `ForeignKey` is concrete (its column is `"desk_id"`); `ManyToManyField` and reverse relations are *not* concrete because no column exists on the table.
- **`local_concrete_fields`**: only the concrete columns physically living on *this* model's own `db_table` (crucial for multi-table inheritance saves!).
- **`many_to_many`**: forward `ManyToManyField` relations (`["beats"]` on our newsroom's `"Story"`).
- **`related_objects`**: every reverse relation pointing *at* this model (`["story_beats", "corrections"]` on `"Story"`).

Notice how `Options.get_field` (`django/db/models/options.py:Options.get_field`) deliberately splits lookups into **two** cached dictionaries — `_forward_fields_map` (`FORWARD_PROPERTIES`) and `fields_map` (`REVERSE_PROPERTIES`):

1. First it checks `_forward_fields_map`, which maps both `Field.name` (`"desk"`) *and* `Field.attname` (`"desk_id"`, `django/db/models/fields/__init__.py:Field`) to the exact same `ForeignKey` instance — without touching any other model in the project.
2. Only on a miss does it check `Apps.models_ready` (`django/apps/registry.py:Apps`) and build `fields_map` by traversing the project-wide `_relation_tree`. Splitting forward and reverse caches lets Django resolve forward fields safely during import time before every app's models have loaded, and lets `Options.add_field` invalidate only the affected half (`_expire_cache(forward=False)` vs `_expire_cache(reverse=False)`).

Inspect `Options` and `Field` metadata live on our newsroom's `"Story"` model:

```text recording=ch06-models
Options (_meta) and Field metadata on Story
  db_table='newsroom_story' pk='id' (BigAutoField, auto_created=True)
  concrete_fields (10): ['id', 'headline', 'slug', 'body', 'priority', 'status', 'published_at', 'desk', 'reporter', 'edition']
  many_to_many (1): ['beats']
  related_objects (2): ['story_beats', 'corrections']
  'desk' in _forward_fields_map: True, 'desk_id' in _forward_fields_map: True
  mutating concrete_fields -> AttributeError: The return type of 'concrete_fields' should never be mutated. If you want to manipulate this list for your own use, make a copy first.
  priority db_type='smallint unsigned' db_check='"priority" >= 0'
  slug.deconstruct() -> ('slug', 'django.db.models.SlugField', [], {'max_length': 160, 'unique': True})
```

Look at line 22: calling `list.append` on `concrete_fields` raises `AttributeError` immediately because `ImmutableList` subclasses `tuple` and prints a tailored warning whenever code tries to mutate a shared cached field list!

## How a model field bridges Python, SQL, and validation

Every `Field` (`django/db/models/fields/__init__.py:Field`) simultaneously plays four roles across Django's stack:

1. **Schema translation (`Field.db_type` and `Field.db_check`, lines 883–955):** `db_type(connection)` looks up `Field.get_internal_type` inside the backend's `BaseDatabaseWrapper.data_types` (`django/db/backends/base/base.py:BaseDatabaseWrapper`) dictionary (`"PositiveSmallIntegerField"` → `"smallint unsigned"` on SQLite), while `db_check(connection)` looks up `BaseDatabaseWrapper.data_type_check_constraints` (`'"priority" >= 0'`). That single indirection is how one Python model generates PostgreSQL `"smallint"`, SQLite `"smallint unsigned"`, and MySQL `"smallint UNSIGNED"` without backend `if` statements in your models.
2. **Python-to-SQL value preparation (`Field.get_prep_value` and `Field.get_db_prep_value`, lines 1030–1055):** Before binding query parameters, `get_prep_value` converts Python objects into backend-neutral primitives (resolving lazy `Promise` values, normalizing datetimes or `uuid.UUID` values); `get_db_prep_value` then applies backend-specific adaptation (such as formatting a `uuid.UUID` with or without hyphens depending on the database driver).
3. **SQL-to-Python conversion (`Field.get_db_converters`, lines 959–962):** Notice the performance guard on line 960: `Field` does **not** define a default `from_db_value` method! Only field subclasses that genuinely need post-processing on cursor values (like `django.db.models.JSONField` calling `json.loads`, or `UUIDField` wrapping strings into `uuid.UUID`) define `from_db_value`, so `SQLCompiler` pays zero per-cell Python callback overhead for plain `CharField` or `IntegerField` columns!
4. **Validation (`Field.clean`, lines 869–878):** Calls `to_python(value)` → `validate(value, model_instance)` (checking `choices`, `null`, and `blank`) → `run_validators(value)`. Crucially, **`Model.save` NEVER calls `Model.full_clean` or `Field.clean`!** Validation runs inside `ModelForm` (Chapter 10) or when you call `full_clean()` explicitly; saving directly in Python trusts your Python types and leaves enforcement to database constraints.

## Serialization for migrations: `django.db.models.Field.deconstruct`

How does `"makemigrations"` turn a live Python `django.db.models.SlugField` object in memory into clean, minimal Python source code inside `"0001_initial.py"`?

Open **`Field.deconstruct`** (`django/db/models/fields/__init__.py:Field.deconstruct`). Every `Field` returns a 4-tuple **`(name, path, args, kwargs)`** — as you saw in line 24 of the recording above:

```python
('slug', 'django.db.models.SlugField', [], {'max_length': 160, 'unique': True})
```

Look closely at what `deconstruct()` deliberately omits and normalizes:
- It shortens internal paths (`django.db.models.fields.SlugField` → `django.db.models.SlugField`) so migrations stay insulated from internal module reorganizations.
- It compares every attribute against `Field.__init__`'s defaults and **drops any argument equal to its default** (`null=False`, `blank=False`, `db_index=True` on `SlugField` are omitted), keeping migration diffs minimal.
- `ForeignKey.deconstruct` (`django/db/models/fields/related.py:ForeignKey.deconstruct`) normalizes `to` into lowercase `"app_label.model_name"` and wraps swappable targets like `AUTH_USER_MODEL` in `SettingsReference` so changing `AUTH_USER_MODEL` never hardcodes `"auth.user"` into third-party migrations!

## Where `django.db.models.options.Options` and fields leak

- **Skipping `full_clean()` lets invalid `choices`, `max_length`, and `blank=False` values straight into SQLite.** Because `Model.save` skips `django.db.models.Field.clean`, and SQLite treats `"VARCHAR(160)"` as unbounded `TEXT`, saving a 500-character headline or an unlisted status string succeeds silently unless you validate via a `ModelForm`, call `full_clean()`, or add a `CheckConstraint`.
- **Custom fields that forget to override `deconstruct()` break `"makemigrations"`.** If you subclass `django.db.models.CharField` and add a custom `__init__` parameter without returning it in `deconstruct()`, Django's migration autodetector cannot serialize or detect changes to that parameter.
- **Calling `django.db.models.options.Options.get_field` for a reverse relation during import time raises `FieldDoesNotExist`.** Because `Apps.models_ready` is still `False` while models are being imported, reverse lookups fail until `Apps.populate` finishes — use `Apps.ready` (`AppConfig.ready`) or `lazy_related_operation` instead.

We now know where field metadata lives on the class. Next, we trace what happens the instant your code reads `"story.body"`, `"story.desk_id"`, or `"story.desk"` on a live instance in [Attribute access, deferred fields, and relations](descriptors.md).
