classMigrationRecorder:"""
Deal with storing migration records in the database.
Because this table is actually itself used for dealing with model
creation, it's the one thing we can't do normally via migrations.
We manually handle table creation/schema updating (using schema backend)
and then have a floating model to do queries with.
If a migration is unapplied its row is removed from the table. Having
a row in the table always means a migration is applied.
"""_migration_class=None@classpropertydefMigration(cls):"""
Lazy load to avoid AppRegistryNotReady if installed apps import
MigrationRecorder.
"""ifcls._migration_classisNone:classMigration(models.Model):# 定义迁移模型类app=models.CharField(max_length=255)# 应用名称name=models.CharField(max_length=255)# 迁移文件名applied=models.DateTimeField(default=now)# 操作时间classMeta:apps=Apps()# App对象app_label="migrations"# 应用标签db_table="django_migrations"# 表名def__str__(self):return"Migration %s for %s"%(self.name,self.app)cls._migration_class=Migrationreturncls._migration_class# 返回迁移类def__init__(self,connection):self.connection=connection
defapplied_migrations(self):"""
Return a dict mapping (app_name, migration_name) to Migration instances
for all applied migrations.
"""ifself.has_table():return{# 用元组表示key,用迁移记录表示value(migration.app,migration.name):migrationformigrationinself.migration_qs}else:# If the django_migrations table doesn't exist, then no migrations# are applied.return{}
相关的类方法解释
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
defrecord_applied(self,app,name):"""Record that a migration was applied."""self.ensure_schema()self.migration_qs.create(app=app,name=name)# 数据库生成一条migrations记录defrecord_unapplied(self,app,name):"""Record that a migration was unapplied."""self.ensure_schema()self.migration_qs.filter(app=app,name=name).delete()# 数据库删除一条migrations记录defflush(self):"""Delete all migration records. Useful for testing migrations."""self.migration_qs.all().delete()# 数据库清空migrations记录