Models and migrations
Model your data, create migrations and keep schema changes reviewable.
What you will be able to do
- Define fields and relationships on the model.
- Run makemigrations then migrate.
- Add __str__ for readable admin labels.
- Never edit a migration that has already run in production.
In plain English
A model is a Python class that maps to a database table. Migrations record schema changes so every environment can reach the same state. Make small migrations and read them before applying.
from django.db import models
class Course(models.Model):
slug = models.SlugField(unique=True)
title = models.CharField(max_length=120)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self) -> str:
return self.title
class Lesson(models.Model):
course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE)
title = models.CharField(max_length=160)
minutes = models.PositiveSmallIntegerField(default=10)Your turn
EasyAdd a published flag
Add a boolean published field that defaults to False.
PYTHON · starter
published =Check your understanding before moving on.
Knowledge checkQuestion 1
Which command creates a migration file from model changes?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.