14

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"
funnydman
  • 9,083
  • 4
  • 40
  • 55
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162

3 Answers3

26

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.

creyD
  • 1,972
  • 3
  • 26
  • 55
5

To store information about applied migrations Django uses plain table and it is accessible as @classproperty through the MigrationRecorder class:

from django.db.migrations.recorder import MigrationRecorder

lm = MigrationRecorder.Migration.objects.filter(app='core').last()

It is also easy to retrieve this information from the command line:

Get the last applied migration for the particular app

python manage.py showmigrations --list <app_name> | grep "\[X\]" | tail -1

Get the ordered list of unapplied migrations

python manage.py showmigrations --plan | grep "\[ \]"
funnydman
  • 9,083
  • 4
  • 40
  • 55
  • Can you check this: https://stackoverflow.com/questions/64639768/unable-to-migrate-using-modelstate-and-projectstate-using-of-migrations-api-in-d unable to use model_create as well as projectstate and modelstate as well to apply migrations. The fields have been specified right and have tried even the testcase way of creating models. Do I have to call addfield removefield specifically in migrations? – Gary Nov 04 '20 at 13:03
-2

A lot easier, you could also parse out the last line of:

./manage.py showmigrations <app_name>

Amjad Abdelrahman
  • 3,372
  • 1
  • 13
  • 20
Alper
  • 3,424
  • 4
  • 39
  • 45
  • This won't work as the output of showmigrations is ordered by app name, and the last line could be a migration that hasn't run yet. @Dariem Pérez Herrera's solution is the correct way imo – Dean Nov 11 '19 at 04:16