Creating Models
Creating Models
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.
1. Defining a Model Class
Every model inherits from django.db.models.Model. Each class attribute represents a database column.
2. Model Field Options
Django field definitions accept universal configuration options:
null=True: Allows the database column to storeNULLvalues. (Avoid onCharField/TextFieldwhere 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 SQLUNIQUEconstraint on the column.db_index=True: Creates an SQL B-tree index on the column for accelerated lookup speeds.
3. The auto_now vs auto_now_add Timestamp Rule
auto_now_add=True: Automatically sets the field tonow()when the object is first created. Ideal forcreated_at.auto_now=True: Automatically updates the field tonow()every time the record is saved viasave(). Ideal forupdated_at.
4. Generating and Applying SQL Migrations
Whenever you create or modify a model:
Practice Quiz
Field Types & Relationships
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Creating First Django App | Field Types & Relationships |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.