ποΈ
Introduction to Django Models
Django models are Python classes that define the structure of your database tables. Each model maps to a single database table, and each attribute maps to a column. Django's ORM lets you interact with databases using Python - no raw SQL needed.
20 minβ’By Priygop Teamβ’Updated 2026
What Are Models?
- A model is a Python class that subclasses django.db.models.Model
- Each class attribute = a database column
- Django auto-creates the database table from the model
- Models are defined in app/models.py
- Django adds an auto-incrementing 'id' primary key by default
- Models define both schema AND behavior (methods)
- Changes to models require migrations to update the database
First Model
First Model
# blog/models.py
# from django.db import models
# from django.utils import timezone
# class Post(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(unique=True)
# content = models.TextField()
# author = models.CharField(max_length=100)
# created_at = models.DateTimeField(default=timezone.now)
# updated_at = models.DateTimeField(auto_now=True)
# published = models.BooleanField(default=False)
#
# def __str__(self):
# return self.title
#
# class Meta:
# ordering = ['-created_at']
# verbose_name_plural = 'Posts'
# After defining the model:
# python manage.py makemigrations # Create migration file
# python manage.py migrate # Apply to database?? Tip
Tip
Each Django model maps to one database table. Use CharField for short text, TextField for long content, and DateTimeField for timestamps.
Diagram
Loading diagramβ¦
QuerySets are LAZY - no DB hit until evaluated.
?? Common Mistake
Warning
Not setting on_delete for ForeignKey. Django requires it. Use CASCADE for child deletion, PROTECT to prevent parent deletion.
?? Practice Task
Note
(1) Create a model with CharField, IntegerField, DateField. (2) Add __str__ method. (3) Run makemigrations and migrate.
Quick Quiz
Key Takeaways
- Django models are Python classes that define the structure of your database tables.
- A model is a Python class that subclasses django.db.models.Model
- Each class attribute = a database column
- Django auto-creates the database table from the model