Django Models, Migrations and the Admin: From a Post Class to a Real Table
A Post model with three fields becomes the blog_post table. makemigrations writes the plan, sqlmigrate shows the SQL, migrate runs it, the ORM saves and finds posts, and two lines in admin.py give you a back office.
What you will learn
- Write a Django model and explain how its fields become columns
- Run makemigrations, read the migration file and preview its SQL with sqlmigrate
- Apply migrations with migrate and check the result with showmigrations
- Save and query posts with the ORM, then manage them in the admin
Before you start
- A Django project with an app
- SQL basics: tables, rows, SELECT
A page that says "welcome" is nice, but a blog needs posts that stay saved, even after the server stops. In Django that's the job of a model and the database behind it. Once the data is there, the admin lets you manage it without writing a single page.
Think of the pantry in a kitchen. Before you build a shelf, you draw its plan, with a space for each thing. That plan is the model. Then you write a work order that says "build this shelf", so any kitchen can build the same one. That's a migration. The builder follows the order and now the shelf exists: that's migrate, and the pantry is the database. The helper who puts things on the shelf and fetches them for you is the ORM. And the clipboard by the door, where the manager checks and edits the stock, is the admin.
The Post model
Here's the plan for our shelf, in 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
Postinherits frommodels.Model. That's what makes it a model.- Each attribute is a field, and each field becomes a column.
titleis short text, at most 200 characters.bodyis long text. createdis a date and time.auto_now_add=Truemeans Django fills in the time itself when a post is first saved.- We never wrote an
id, but Django adds one: a number that goes up for every new post. __str__returns the title, so wherever Django shows a post (the shell, the admin) you see its title.
One class becomes one table, and every object you save becomes one row. The table lives in SQLite, in the db.sqlite3 file that DATABASES in settings.py points to. Django looks inside blog for models because blog is in INSTALLED_APPS.
makemigrations writes the plan down
So far the model is only Python. There's no table yet.
uv run python manage.py makemigrations
uv run python manage.py showmigrations blog
Migrations for 'blog':
blog\migrations\0001_initial.py
+ Create model Post
blog
[ ] 0001_initial
Django compares your models with what it has recorded, finds a new Post, and writes 0001_initial.py in blog/migrations. showmigrations lists it with an empty box: the work order is written, but nobody has carried it out. The database hasn't changed.
Inside the migration file
# Generated by Django 6.1.3 on 2026-11-09 00:51
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('body', models.TextField()),
('created', models.DateTimeField(auto_now_add=True)),
],
),
]
It's plain Python. initial = True because it's this app's first migration, and dependencies is empty because nothing has to run before it. The one operation, CreateModel, lists the fields from the model, plus the id we never wrote: a BigAutoField primary key. Keep these files in your project. Together they are the history of how your tables changed.
sqlmigrate shows the SQL
uv run python manage.py sqlmigrate blog 0001
BEGIN;
--
-- Create model Post
--
CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(200) NOT NULL, "body" text NOT NULL, "created" datetime NOT NULL);
COMMIT;
The table name is the app name, then the model name: blog_post. title becomes varchar(200), body becomes text, created becomes datetime, and every column is NOT NULL. BEGIN and COMMIT wrap it so it happens all together. sqlmigrate only prints the SQL; it doesn't run it, so it's a safe way to read what a migration will do.
migrate builds the tables
uv run python manage.py migrate
(Output trimmed in the middle.)
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
...
Applying auth.0012_alter_user_first_name_max_length... OK
Applying blog.0001_initial... OK
Applying sessions.0001_initial... OK
The built-in apps (admin, auth, contenttypes, sessions) have tables of their own, so their migrations run too. Our blog.0001_initial is in the list. Now showmigrations shows an X:
blog
[X] 0001_initial
Django keeps that record in a table called django_migrations, so it never runs the same migration twice. These are all the tables in db.sqlite3 now:
auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_user_permissions blog_post django_admin_log django_content_type django_migrations django_session sqlite_sequence
auth_user will hold our users, and blog_post is ours.
Saving and fetching posts with the ORM
The project has a small script, explore.py, run with manage.py shell so Django is set up first. It also prints every SQL statement Django sent:
from django.db import connection, reset_queries
from blog.models import Post
reset_queries()
p = Post.objects.create(title="Hello", body="First")
print("created:", p.id, p.title)
Post.objects.create(title="Packing a bag", body="Bags")
Post.objects.create(title="A simple pasta", body="Boil")
print("count:", Post.objects.count())
found = Post.objects.filter(title__contains="pa")
print("filter:", [x.title for x in found])
one = Post.objects.get(id=1)
print("get:", one.title, "|", one.body)
for q in connection.queries:
print(q["sql"])
created: 1 Hello
count: 3
filter: ['Packing a bag', 'A simple pasta']
get: Hello | First
INSERT INTO "blog_post" ("title", "body", "created") VALUES ('Hello', 'First', '2026-11-09 00:51:54.087054') RETURNING "blog_post"."id"
INSERT INTO "blog_post" ("title", "body", "created") VALUES ('Packing a bag', 'Bags', '2026-11-09 00:51:54.102343') RETURNING "blog_post"."id"
INSERT INTO "blog_post" ("title", "body", "created") VALUES ('A simple pasta', 'Boil', '2026-11-09 00:51:54.114875') RETURNING "blog_post"."id"
SELECT COUNT(*) AS "__count" FROM "blog_post"
SELECT "blog_post"."id", "blog_post"."title", "blog_post"."body", "blog_post"."created" FROM "blog_post" WHERE "blog_post"."title" LIKE '%pa%' ESCAPE '\'
SELECT "blog_post"."id", "blog_post"."title", "blog_post"."body", "blog_post"."created" FROM "blog_post" WHERE "blog_post"."id" = 1 LIMIT 21
Read the Python and the SQL side by side:
| Python | SQL Django sent | Result |
|---|---|---|
Post.objects.create(...) | INSERT INTO "blog_post" ... | new row, id 1; created filled in |
.count() | SELECT COUNT(*) | 3 |
.filter(title__contains="pa") | WHERE title LIKE '%pa%' | two posts |
.get(id=1) | WHERE id = 1 | exactly one post, Hello |
objects is the manager, our helper. create builds the object and saves it in one go. filter gives you a group of matches, and get gives you one object. You wrote no SQL: the ORM turns Python calls into SQL, and rows back into objects. If you want to compare with hand-written SQL, see SQL essentials.
The admin
A superuser to log in with
To log in to the admin you need a user who's allowed in, a superuser:
uv run python manage.py createsuperuser
Normally it asks for a username, an email and a password. In the lecture's recorded run the values came from environment variables with --noinput, using a test user, and it printed:
Superuser created successfully.
A new row lands in auth_user. For any real project, pick a strong password and never share it.
Registering Post
Open blog/admin.py:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
That one line tells the admin to build pages for our model. The admin itself is already wired in: in blogproject/urls.py, the path admin/ goes to admin.site.urls. Run the server, go to /admin, log in, and Blog shows up with Posts next to the built-in groups and users. The lecture's run checked each admin page with the test client:
login /admin/login/ 200
index /admin/ 200
list /admin/blog/post/ 200
add /admin/blog/post/add/ 200
change /admin/blog/post/1/change/ 200
The list page sends a SELECT through the Post model, and each row shows its title, thanks to __str__. The add form has Title and Body, taken straight from the fields. There's no box for created, because auto_now_add fills it in. A title opens its change page at /admin/blog/post/1/change/, where you can edit or delete the post. From two lines in admin.py you get a list, a form and an edit page.
Working with models from now on
- Change the model, for example add a field.
- Run
makemigrations. A new numbered migration file appears. - Read that file, the same way you'd review a diff from an AI agent, before you trust it.
- Run
migrate, and the table changes to match.
When you ask an AI tool for a model change, ask for the model change and the migration together, then review both.
Common mistakes
- Changing the model and forgetting
makemigrations. The table doesn't change until a migration exists and is applied. - Running
makemigrationsand thinking you're done. It only writes the plan;migrateruns it. - Deleting migration files. Together they are the history of how your tables changed, and other copies of the project need them to build the same tables.
- Using
getwhen there might be several matches or none.getexpects exactly one row; usefilterfor groups.
Quick recap
| Step | Command or code | What changes |
|---|---|---|
| Describe the data | class Post(models.Model) | nothing in the database yet |
| Write the plan | makemigrations | 0001_initial.py appears |
| Read the SQL | sqlmigrate blog 0001 | nothing; it only prints |
| Build the table | migrate | blog_post exists, box gets an X |
| Use the data | create, filter, get | rows in, objects out |
| Manage it | admin.site.register(Post) | list, add and change pages |
Try it yourself
Add a short summary field to Post, run makemigrations and read the new file, then migrate, and add a post with a summary in the admin.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)