Python Academy · Lesson

Models and Migrations

Define and migrate the database.

Lesson 2 of 413 steps

Models and Migrations is a free Python Academy lesson on CoddyKit. This is lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.

Django Models

A Django model is a Python class that defines the structure of a database table. Each attribute is a field. Models live in an app's models.py.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
print('Post model defined')

Field Types

Django provides many field types that map to column types.

  • CharField for short text (needs max_length)
  • TextField for long text
  • IntegerField, BooleanField, DateTimeField
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    views = models.IntegerField(default=0)
print('Fields map to columns')

The Implicit Primary Key

Django automatically adds an auto-incrementing id primary key to every model, so you rarely declare one yourself.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    # 'id' is added automatically
print('id field is automatic')

Field Options

Fields accept options like default, null, blank, and unique to control behavior and validation.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    published = models.BooleanField(default=False)
    subtitle = models.CharField(max_length=200, blank=True)
print('Options refine each field')

Dates

DateTimeField(auto_now_add=True) records when a row is first created. auto_now=True updates on every save.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
print('Timestamps set automatically')

Relationships

Link models with ForeignKey for one-to-many. on_delete tells Django what to do when the referenced row is deleted.

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Post(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
print('ForeignKey links Post to Author')

What Are Migrations?

Migrations are Django's way of turning model changes into database schema changes. They are version control for your database.

# Migrations record schema changes over time
# so the database matches your models
print('Migrations track schema changes')

makemigrations

python manage.py makemigrations inspects your models and generates migration files describing the changes.

# python manage.py makemigrations
# -> blog/migrations/0001_initial.py
print('makemigrations writes migration files')

migrate

python manage.py migrate applies pending migrations to the database, creating or altering tables.

# python manage.py migrate
# -> Applying blog.0001_initial... OK
print('migrate applies changes to the DB')

The Migration Workflow

The cycle is: edit models.py, run makemigrations, then run migrate. Repeat whenever your models change.

# 1. Change models.py
# 2. python manage.py makemigrations
# 3. python manage.py migrate
print('Edit, make, migrate')

Querying Models

Each model gets a manager called objects for queries: Post.objects.all(), .filter(), .get(), and .create().

# Post.objects.all()
# Post.objects.filter(published=True)
# Post.objects.get(id=1)
# Post.objects.create(title='Hello')
print('objects is the query manager')

Quick Check

Test your migrations knowledge.

Recap

You defined models and migrated them.

  • Models are classes in models.py with typed fields
  • Django adds an automatic id primary key
  • ForeignKey links models; on_delete sets cascade behavior
  • makemigrations then migrate syncs the database
  • Model.objects queries the data
Free to start

Learn Python with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
76
Lessons
320

Frequently Asked Questions

Is the “Models and Migrations” lesson free?

Yes — the full text of “Models and Migrations” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 4 lessons in total.

What will I learn in “Models and Migrations”?

Define and migrate the database. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Models and Migrations” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Projects and Apps
  2. Models and Migrations
  3. Views and URLs
  4. The Django Admin
← Back to Python Academy