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

问题描述 投票:5回答:3

我想获取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"
python django django-migrations
3个回答
6
投票

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

0
投票

为了存储有关已应用迁移的信息,Django使用普通表,可通过@classproperty类将其作为MigrationRecorder进行访问:

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 "\[ \]"

-1
投票

更容易,您也可以解析出以下内容的最后一行:

./manage.py show migrations <app_name>

© www.soinside.com 2019 - 2024. All rights reserved.