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 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:
concrete_fields: every concrete field (field, meaning.concrete is True field— a real column in SQL) across the model and its concrete parents..column is not None ForeignKeyis concrete (its column is"desk_id");ManyToManyFieldand 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 owndb_table(crucial for multi-table inheritance saves!).many_to_many: forwardManyToManyFieldrelations (["beats"]on our newsroom’s"Story").related_objects: every reverse relation pointing at this model (["story_beats", "corrections"]on"Story").
Notice how Options deliberately splits lookups into two cached dictionaries — _forward_fields_map (FORWARD_PROPERTIES) and fields_map (REVERSE_PROPERTIES):
- First it checks
_forward_fields_map, which maps bothField.name("desk") andField.attname("desk_id",Field) to the exact sameForeignKeyinstance — without touching any other model in the project. - Only on a miss does it check
Appsand build.models_ready fields_mapby 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 letsOptionsinvalidate only the affected half (.add_field _expire_cache(forward=False)vs_expire_cache(reverse=False)).
Inspect Options and Field metadata live on our newsroom’s "Story" model:
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:
- Schema translation (
Field.db_typeandField.db_check, lines 883–955):db_type(connection)looks upFieldinside the backend’s.get_internal_type BaseDatabaseWrapperdictionary (.data_types "PositiveSmallIntegerField"→"smallint unsigned"on SQLite), whiledb_check(connection)looks upBaseDatabaseWrapper(.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 backendifstatements in your models. - Python-to-SQL value preparation (
Fieldand.get_prep_value Field, lines 1030–1055): Before binding query parameters,.get_db_prep_value get_prep_valueconverts Python objects into backend-neutral primitives (resolving lazyPromisevalues, normalizing datetimes oruuid.UUIDvalues);get_db_prep_valuethen applies backend-specific adaptation (such as formatting auuid.UUIDwith or without hyphens depending on the database driver). - SQL-to-Python conversion (
Field, lines 959–962): Notice the performance guard on line 960:.get_db_converters Fielddoes not define a defaultfrom_db_valuemethod! Only field subclasses that genuinely need post-processing on cursor values (likedjangocalling.db .models .JSONField json.loads, orUUIDFieldwrapping strings intouuid.UUID) definefrom_db_value, soSQLCompilerpays zero per-cell Python callback overhead for plainCharFieldorIntegerFieldcolumns! - Validation (
Field.clean, lines 869–878): Callsto_python(value)→validate(value, model_instance)(checkingchoices,null, andblank) →run_validators(value). Crucially,Model.saveNEVER callsModel.full_cleanorField.clean! Validation runs insideModelForm(Chapter 10) or when you callfull_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 object in memory into clean, minimal Python source code inside "0001_initial?
Open Field. 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:
- It shortens internal paths (
django→.db .models .fields .SlugField django) so migrations stay insulated from internal module reorganizations..db .models .SlugField - It compares every attribute against
Field.__init__'s defaults and drops any argument equal to its default (null=False,blank=False,db_index=TrueonSlugFieldare omitted), keeping migration diffs minimal. ForeignKeynormalizes.deconstruct tointo lowercase"app_labeland wraps swappable targets like.model_name" AUTH_USER_MODELinSettingsReferenceso changingAUTH_USER_MODELnever hardcodes"auth.user"into third-party migrations!
Where django.db.models.options.Options and fields leak
- Skipping
full_clean()lets invalidchoices,max_length, andblank=Falsevalues straight into SQLite. BecauseModel.saveskipsdjango, and SQLite treats.db .models .Field .clean "VARCHAR(160)"as unboundedTEXT, saving a 500-character headline or an unlisted status string succeeds silently unless you validate via aModelForm, callfull_clean(), or add aCheckConstraint. - Custom fields that forget to override
deconstruct()break"makemigrations". If you subclassdjangoand add a custom.db .models .CharField __init__parameter without returning it indeconstruct(), Django’s migration autodetector cannot serialize or detect changes to that parameter. - Calling
djangofor a reverse relation during import time raises.db .models .options .Options .get_field FieldDoesNotExist. BecauseAppsis still.models_ready Falsewhile models are being imported, reverse lookups fail untilApps.populatefinishes — useApps.ready(AppConfig.ready) orlazy_related_operationinstead.
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.