如何以编程方式获取上次迁移的名称?

How to get a name of last migration programmatically?

我想在 Django 中获取上次应用的迁移的名称。我知道 Django 迁移存储在 django_migrations table 中,但是 django.db.migrations.migration.Migration 不是由 table 支持的 models.Model。这意味着你不能这样做:

migration_info = Migration.objects.all()

是否有任何从 django_migrations 检索数据的内置方法,或者我应该创建自己的只读模型:

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

这适用于 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

似乎没有此命令的文档,但here您可能会找到正确记录的源代码。

容易多了,你也可以解析出最后一行:

./manage.py showmigrations <app_name>

为了存储有关应用迁移的信息,Django 使用纯 table 并且可以通过 MigrationRecorder class:

作为 @classproperty 访问它
from django.db.migrations.recorder import MigrationRecorder

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

从命令行检索此信息也很容易:

获取特定应用程序的最后应用迁移

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

获取未应用迁移的有序列表

python manage.py showmigrations --plan | grep "\[ \]"