Models & DatabaseCore· 40 min read

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.

A Post model = a database table
# 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.title

Reading 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:

Migrations build/update your database
python manage.py makemigrations   # create the migration file
python manage.py migrate          # build the table in the database

How the migration process works, step by step:

  1. You add or change a model in models.py (like the Post class above).
  2. makemigrations compares 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").
  3. migrate runs that plan against the real database, actually creating or altering the tables.
  4. 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?

Answer: makemigrations creates the migration; migrate applies it to the database.

✍️ Practice

  1. Create a Post model and run the migrations.
  2. Add a field, then makemigrations + migrate again.

🏠 Homework

  1. Create models for a simple shop: Product and Category.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →