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"
You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. How can I find out which migrations are unapplied without running migrate? One way to do this is to look at the django_migrations table in the DB and check which ones are applied.
Django Migrations Custom names for migration filesUse the makemigrations --name <your_migration_name> option to allow naming the migrations(s) instead of using a generated name.
Django keeps track of applied migrations in the Django migrations table. Django migrations consist of plain Python files containing a Migration class. Django knows which changes to perform from the operations list in the Migration classes. Django compares your models to a project state it builds from the migrations.
migrate , which is responsible for applying and unapplying migrations. makemigrations , which is responsible for creating new migrations based on the changes you have made to your models.
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.
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:
python manage.py showmigrations --list <app_name> | grep "\[X\]" | tail -1
python manage.py showmigrations --plan | grep "\[ \]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With