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

时间:2016-03-02 10:04:48

标签: python django django-migrations

我想获得Django中最后一次应用迁移的名称。我知道django迁移存储在django_migrations表中,但django.db.migrations.migration.Migration不是该表支持的models.Model。这意味着您无法做到:

migration_info = Migration.objects.all()

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

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

3 个答案:

答案 0 :(得分:4)

这适用于Django 1.11:

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

答案 1 :(得分:0)

要存储有关已应用迁移的信息,Django使用纯表,可通过MigrationRecorder类以@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 "\[ \]"

答案 2 :(得分:-1)

容易得多,您还可以解析以下内容的最后一行:

./manage.py show migrations <app_name>