我想获取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"
这适用于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
为了存储有关已应用迁移的信息,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 "\[ \]"
更容易,您也可以解析出以下内容的最后一行:
./manage.py show migrations <app_name>