Django's Object-Relational Mapper (ORM) allows you to define your database schema using clean, idiomatic Python classes. A Django model is the single, definitive source of truth about your data: it contains the essential fields and behaviors of the data you're storing. Django automatically maps model classes to SQL database tables and handles migrations without writing raw SQL.
Every model inherits from django.db.models.Model. Each class attribute represents a database column.
Django field definitions accept universal configuration options:
null=True: Allows the database column to store NULL values. (Avoid on CharField/TextField where Django conventions prefer empty strings "").blank=True: Controls form/admin validation; allows the field to be submitted empty in web forms.default=value: Default value assigned when creating a new record.unique=True: Enforces an SQL UNIQUE constraint on the column.db_index=True: Creates an SQL B-tree index on the column for accelerated lookup speeds.auto_now vs auto_now_add Timestamp Ruleauto_now_add=True: Automatically sets the field to now() when the object is first created. Ideal for created_at.auto_now=True: Automatically updates the field to now() every time the record is saved via save(). Ideal for updated_at.Whenever you create or modify a model:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Creating First Django App | Field Types & Relationships |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.