The Django migration system is designed to handle a large number of migrations efficiently. Generally, it’s okay to maintain numerous model migrations in your codebase, even though they might slow down tests or cause other issues. If you need to clean up migrations, here are some straightforward options.
Scenario 1: Full Cleanup in Development
If your project is still in development and you don’t mind resetting the entire database, follow these steps:
Step 1: Remove All Migration Files
Navigate to each app’s migration folder and delete everything inside except for the __init__.py
file. Alternatively, use this Unix command:
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
Step 2: Drop the Database
Delete the existing database file (e.g., db.sqlite3
).
Step 3: Create Initial Migrations
Run the following commands to create initial migrations and generate the database schema:
python manage.py makemigrations
python manage.py migrate
And you’re good to go!
Scenario 2: Clear Migration History but Keep the Database
If you want to clear the migration history while retaining the existing database, follow these steps:
Step 1: Ensure Models Match the Current Schema
Try creating new migrations to check for pending migrations:
python manage.py makemigrations
If you see “No changes detected,” proceed to the next step.
Step 2: Clear Migration History for Each App
Clear the migration history app by app. First, run the showmigrations
command:
python manage.py showmigrations
Clear the migration history for each app, replacing “core” with your app name:
python manage.py migrate --fake my_app zero
Step 3: Remove Migration Files
Delete all migration files except for the __init__.py
file. Use the following script:
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
Step 4: Create Initial Migrations
Run the command to create initial migrations again:
python manage.py makemigrations
Step 5: Fake the Initial Migration
If the database tables already exist, fake the initial migration:
python manage.py migrate --fake-initial
Finally, check your migrations with:
python manage.py showmigrations
And that’s it! You’ve successfully cleaned up your Django migration history.