Creating Models0%

Creating Models

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

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.

Python
# articles/models.py
from django.db import models
from django.utils.text import slugify
 
class Article(models.Model):
# Core data fields
title = models.CharField(max_length=200, help_text="Article headline")
slug = models.SlugField(max_length=200, unique=True, db_index=True)
content = models.TextField()
# Status choices
STATUS_CHOICES = [
("draft", "Draft"),
("published", "Published"),
("archived", "Archived"),
]
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="draft")
# Numerical and Boolean fields
view_count = models.PositiveIntegerField(default=0)
is_featured = models.BooleanField(default=False)
# Automatic audit timestamps
created_at = models.DateTimeField(auto_now_add=True) # Set only upon creation
updated_at = models.DateTimeField(auto_now=True) # Updated on every save()
 
class Meta:
# Table metadata configuration
db_table = "enterprise_articles"
ordering = ["-created_at"] # Default ordering: newest first
verbose_name = "Article"
verbose_name_plural = "Articles"
 
def __str__(self):
return f"{self.title} ({self.status})"
 
def save(self, *args, **kwargs):
# Automatically generate URL slug if empty
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)

2. Model Field Options

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.

3. The auto_now vs auto_now_add Timestamp Rule

  • auto_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.

4. Generating and Applying SQL Migrations

Whenever you create or modify a model:

Bash / Terminal
# 1. Inspect models and generate migration scripts in articles/migrations/
python manage.py makemigrations articles
 
# 2. View raw SQL that Django will execute (optional inspection)
python manage.py sqlmigrate articles 0001
 
# 3. Apply changes to physical database tables
python manage.py migrate

Interactive Quiz

Practice Quiz

Question 1
What class must all Django models inherit from?
Question 2
What is the difference between null=True and blank=True in Django model fields?
Question 3
How does auto_now_add=True differ from auto_now=True on DateTimeField?
Question 4
Why is defining a __str__ method on models considered an enterprise best practice?
Question 5
What command generates Python migration files from modified models without applying them to the database?
Next Lesson

Field Types & Relationships

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext