Search code examples
pythondjangodjango-migrations

How to get a name of last migration programmatically?


I want to get the name of the last applied migration in Django. I know that Django migrations are stored in django_migrations table, however django.db.migrations.migration.Migration is not a models.Model backed by that table. This means you cannot do:

migration_info = Migration.objects.all()

Is there any built-in way of retrieveing the data from django_migrations, or should i just create my own read-only Model:

class MigrationInfo(models.Model):
    class Meta:
         managed = False
         db_table = "django_migrations"

Solution

  • This works on Django 1.11/1.8/2.1 & 3.0.4:

    from django.db.migrations.recorder import MigrationRecorder
    
    last_migration = MigrationRecorder.Migration.objects.latest('id')
    print(last_migration.app)     # The app where the migration belongs
    print(last_migration.name)    # The name of the migration
    

    There doesn't seem to be documentation for this command, but here you may find the source code which is documented properly.