另一种选择是在添加 ForeignKey 之前创建数据迁移,您可以在其中创建具有特定 ID 的新 Player 实例。确保该 ID 以前不存在于您的数据库中。
1.创建数据迁移文件
$ ./manage.py datamigration myapp add_player
Created 00XX_add_player.py
2.编辑文件的前进和后退方法:
def forwards(self, orm):
orm['myapp.Player'].objects.create(name=u'Very misterious player', id=34)
def backwards(self, orm):
# Haven't tested this one yet
orm['myapp.Player'].objects.filter(id=34).delete()
3.将 ForeignKey 添加到您的 Misery 类并再次迁移架构。它将要求您的数据迁移 id 的默认值,在本例中为 34。
$ ./manage.py schemamigration --auto myapp
? The field 'Mistery.player' does not have a default specified, yet is NOT NULL.
? Since you are adding this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> 34
+ Added field player on myapp.Mistery
Created 0010_auto__add_field_mistery_player.py. You can now apply this migration with: ./manage.py migrate myapp
4.最后运行 migrate 命令,它将按顺序执行迁移,插入新 Player 并使用对新 Player 的引用更新所有 Mistery 行。