Models & Migrations
Define your database tables as Python classes — no SQL needed.
What you will learn
- Define a model
- Run migrations
- Understand the ORM
A model is a Python class
A model describes one kind of thing you want to store — here, a blog post. You write it as a Python class, and each attribute becomes a column in a database table. Django reads this class and builds the matching table for you, so you never write SQL by hand.
# blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.titleReading it part by part: the class Post extends models.Model, which makes it a database table. title is a short text column (CharField) limited to 200 characters. body is a long text column (TextField). created is a date/time that Django fills in automatically the moment a post is made (auto_now_add=True). The __str__ method just tells Django to show the post’s title whenever it needs to print the object — handy in the admin and the shell.
Create the table with migrations
Writing the model class does not change the database yet — it is only a description. Migrations are the two-step process that turns your model changes into real tables. Run these two commands in the terminal:
python manage.py makemigrations # create the migration file
python manage.py migrate # build the table in the databaseHow the migration process works, step by step:
- You add or change a model in
models.py(like thePostclass above). makemigrationscompares your models to the last known state and writes a small migration file — a recorded plan of the changes (e.g. "create a Post table with these columns").migrateruns that plan against the real database, actually creating or altering the tables.- Django remembers which migrations have run, so next time it only applies the new ones.
Note: Output (after migrate):
Applying blog.0001_initial... OK
The OK means the Post table now exists in your database, ready to hold real posts.
Note: Django’s ORM lets you work with the database using Python instead of SQL. Post.objects.all() runs a SELECT for you. (Knowing SQL still helps you understand what it does.)
Q. What do you run to build database tables from your models?
✍️ Practice
- Create a
Postmodel and run the migrations. - Add a field, then makemigrations + migrate again.
🏠 Homework
- Create models for a simple shop:
ProductandCategory.