Django 6.1.3

6.2 Models, metaclasses, and state

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, attached to the model as "_meta".

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

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

Notice how 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", 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 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:

Recorded on Django 6.1.3 ch06-models script
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 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 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. Every Field returns a 4-tuple (name, path, args, kwargs) — as you saw in line 24 of the recording above:

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

Look closely at what deconstruct() deliberately omits and normalizes:

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

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.