Django Migrations
A migration is a file that records a change to the tables. Django reads the file to build the database.
Make the migration file
This command writes the migration file for the blog app. The lines below it are the real output.
$ python manage.py makemigrations blog
Migrations for 'blog':
blog/migrations/0001_initial.py
+ Create model PostApply the blog migration
This command applies the blog migration to the database. The lines below it are the real output.
$ python manage.py migrate blog
Operations to perform:
Apply all migrations: blog
Running migrations:
Applying blog.0001_initial... OKThe migration file
The file records one step: create the Post model with its fields. The dated header line is left out.
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=100)),
('body', models.TextField()),
],
),
]Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=[
"django.contrib.contenttypes",
"django.contrib.auth",
],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django.db import connection, models
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"
with connection.schema_editor() as editor:
editor.create_model(Post)
print(connection.introspection.table_names())
post = Post(title="First post", body="Hello from Django.")
print(post.title)
Key points
- makemigrations writes a migration file for a changed model.
- migrate applies the migration files to the database.
- Run makemigrations after each model change.
- Migration files live in a migrations folder inside the app.
- A migration file names the model and the change.
In this example, the setup lines configure Django. The Post class stands for one table with a title and a body. The program creates the table directly. A real project uses migrations for this step. The print shows the list of tables, with blog_post in it. The last lines make one post and print its title.
Note
Change the model, not the migration file. Then run makemigrations again.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which command writes a migration file for a changed model?