#Django-Basic
#Django
Django Migrations
- Migration in Django is to
make changes to your models
- Like deleting, adding a field, etc. into your database schema.
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
- Revert migration to old_state
- Delete the reverted migration_files
- python manage.py makemigrations
- python manage.py migrate
./manage.py migrate product 0013_productpricehikehistory
# Revert all migrations to initial or start
./manage.py migrate my_app zero
Reference