Django Migrations

Migration in Django is to make changes to your models

Like deleting, adding a field, etc. into your database schema.

FAQ: How does Django handle database migrations and why are they important?

6.1 Apply migration

  • Makemigrations
    • Detect changes and prepare database to update
    • It creates migration in ‘my_app/migrations/0001_initial.py’
    • Shows if any changes has been made or not
# All apps
python manage.py makemigrations

# singl3 app
python manage.py makemigrations my_app
  • Sqlmigrate
    • View the actual sql code that runs in database
    • We don’t need to know sql, just use model class in model.py file, which is a feature of Django ORM
python manage.py sqlmigrate my_app mig_file_name
  • Migrate
    • Apply changes to DB, all tables are created/updated
    • The migrate command looks at the INSTALLED_APPS setting and
    • Creates any necessary database tables according to the database settings in your mysite/settings.py file
python manage.py migrate

6.2 Revert Migrations

  • Check migrations files(applied/unapplied)
    • [X] - to show which migrations have been applied
    • [ ] - to shows unapplied migrations
# Show migration files of all apps
python manage.py showmigrations --list

# Show migration files of current app
python manage.py showmigrations accounts
  • Revert
    1. Revert migration to old_state
    2. Delete the reverted migration_files
    3. python manage.py makemigrations
    4. python manage.py migrate
python manage.py migrate model_name migration_file_name 

# Revert all migrations to initial or start
./manage.py migrate my_app zero

FAQ:

Reference