Altering Models with Migrations
In this page:
Adding a New Field
Adding a field to a model and running makemigrations generates an AddField operation. If existing rows exist and the field isn't nullable, Django will prompt for a one-time default value during makemigrations.
Example: Adding a New Field
Giving subtitle a default='' means existing Article rows get an empty subtitle automatically instead of makemigrations asking for one interactively.
class Article(models.Model):
title = models.CharField(max_length=200)
subtitle = models.CharField(max_length=200, default='')
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Removing a Field
Deleting a field from the model and running makemigrations generates a RemoveField operation, which drops that column — and all its data — from the table when migrate runs.
Warning: Once a RemoveField migration is applied, that column's data cannot be recovered.
Example: Removing a Field
After removing a field from Article in models.py, this pair of commands generates and then applies the RemoveField migration.
python manage.py makemigrations blog
python manage.py migrate blog
⚠️ Run this command in your terminal.
Renaming a Field
When makemigrations detects a field was removed and a similarly-typed one was added in the same run, it asks whether this is actually a rename, which preserves existing data instead of losing it.
Note: Answer y to the rename prompt to keep existing data; answering n creates a new empty column instead.
Example: Renaming a Field
Confirming the rename produces a RenameField operation, which keeps every existing row's data instead of dropping and recreating the column.
python manage.py makemigrations
# Did you rename article.title to article.headline? [y/N]
⚠️ Run this command in your terminal.
- Adding a required (non-nullable) field to a model that already has rows, without giving Django a default value to fill in for those existing rows.
- Renaming a field in models.py and letting makemigrations create it as a remove-plus-add instead of confirming it should be treated as a rename.
- Forgetting that removing a field's migration will permanently delete that column's data once migrate runs.
- Any model change — new field, removed field, changed type — needs its own migration.
- Adding a required field to a table with existing rows requires a default value.
- makemigrations will interactively ask about renames versus add/remove when it can't tell them apart.
- Always review the generated migration before running migrate on a production database.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: