• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

Formal Definition

Django Models define the structure and behavior of application data as Python classes inheriting from django.db.models.Model, where each class attribute represents a database field, and the ORM (Object-Relational Mapper) translates Python operations (create, filter, save, delete) into SQL queries against a relational database.

Explanation

The Models/ORM layer solves the impedance mismatch between Python objects and relational tables. Instead of writing SQL, developers define fields (CharField, IntegerField, ForeignKey, ManyToManyField) with constraints (null, blank, unique, choices), and Django handles schema creation (migrations), query generation, and object hydration. The ORM supports relationships, aggregation, annotation, and raw SQL escape hatches.

How It Works

  1. Model defined — Python class with field instances as class attributes
  2. Migration createdmakemigrations inspects model changes, generates schema operations
  3. Migration appliedmigrate executes SQL (CREATE TABLE, ALTER TABLE) on database
  4. Query issuedModel.objects.filter(...) returns lazy QuerySet
  5. SQL generated — QuerySet compiles to SELECT with JOINs for relationships
  6. Results hydrated — Rows converted to model instances (or dicts via .values())
  7. Instance savedinstance.save() generates INSERT or UPDATE

Visual Explanation

models_orm ModelClass class Post(models.Model):    title = CharField()    author = ForeignKey(User) Migration makemigrations → 0001_initial.py ModelClass->Migration 1. Detect changes Manager Post.objects → Manager ModelClass->Manager 3. Default manager Database PostgreSQL CREATE TABLE post (...) Migration->Database 2. Apply schema Instance Post(title='Hi',      author=<User>) Database->Instance 7. Hydrate QuerySet QuerySet .filter(), .exclude() Manager->QuerySet 4. Query API SQL SELECT * FROM post JOIN auth_user ... QuerySet->SQL 5. Compile SQL->Database 6. Execute

Semantic Network

semantic_models_orm THIS Models / ORM PRE1 Database Migrations THIS--PRE1 built from PRE2 Field Classes THIS--PRE2 built from PRE3 Relationship Fields THIS--PRE3 built from OUT1 QuerySet API THIS--OUT1 builds into OUT2 Model Managers THIS--OUT2 builds into OUT3 Admin Panel THIS--OUT3 builds into OUT4 ModelForms Auto-generation THIS--OUT4 builds into OUT5 DRF Serializers THIS--OUT5 builds into CON1 SQLAlchemy (Data Mapper) THIS--CON1 contrasts with CON2 Raw SQL (Psycopg2) THIS--CON2 contrasts with REL1 Transactions (Atomic Blocks) THIS--REL1 related REL2 Signals (pre_save, etc.) THIS--REL2 related

Key Properties

  • Field types map to SQL: CharField→VARCHAR, IntegerField→INTEGER, DateTimeField→TIMESTAMP
  • Relationships: ForeignKey (many-to-one), ManyToManyField, OneToOneField with on_delete behavior
  • Meta options: db_table, ordering, indexes, constraints, unique_together, verbose_name
  • Managers: objects = Manager() customizes default queryset; QuerySet.as_manager() for chainable managers
  • Deferred loading: .only(), .defer() control field selection; select_related/prefetch_related for JOINs

Connections

Edge Cases & Gotchas

  • N+1 queries: Accessing post.author.name in loop → use select_related('author')
  • M2M through table: ManyToManyField creates hidden table; through= for custom intermediate model
  • Default mutable: default=[] shares list across instances; use default=list or default=lambda: []
  • Migration reversibility: RunSQL/RunPython need reverse code; data migrations can break rollback
  • Abstract base classes: abstract = True in Meta prevents table creation; fields inherited