Skip to content
Advertisement

How to list applied migrations from command line?

I had run makemigrations and after that migrate to apply the migration

python manage.py showmigrations
admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
 [X] 0008_alter_user_username_max_length
 [X] 0009_alter_user_last_name_max_length
boards
 [X] 0001_initial
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial

How to find out models in boards from command line?

Advertisement

Answer

You’ll need to use some undocumented APIs for this, but here’s one way:

from django.db import connections
from django.db.migrations.loader import MigrationLoader

loader = MigrationLoader(connections['default'])
loader.load_disk()

After this, loader.disk_migrations will be a dictionary whose keys are (app_name, migration_name) tuples, and whose values are the Migration objects. So iterating loader.disk_migrations.keys() will give you a list close to what you want, and you can just format it as desired.

If you want only the ones that have been applied:

from django.db.migrations.recorder import MigrationRecorder
recorder = MigrationRecorder(connections['default'])

And then access recorder.applied_migrations()

If you want to learn a lot about how migrations work internally, and how Django figures out what migrations you have and which are applied, check out the source code of the manage.py migrate command.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement