我有一个模型
class Mystery(models.Model):
first = models.CharField(max_length=256)
second = models.CharField(max_length=256)
third = models.CharField(max_length=256)
player = models.ForeignKey(Player)
我添加了玩家ForeignKey,但当我试图使用南迁移它时,似乎我不能创建这个null=False。我有这个消息:
这个领域的奥秘。player'未指定默认值,但不为NULL。由于要添加此字段,因此必须指定用于现有行的默认值。您想:
1。现在退出,并向模型中的字段添加默认值。py
2。指定要立即用于现有列的一次性值
我使用这个命令:
管理py schemamigration myapp--自动
谢谢!
这最好在3次迁移中完成。
第一步。创建新模型并允许player为空:player=models。外键(Player,null=True)
第二步。运行/管理py模式迁移
第三步。运行/管理py数据迁移
第四步。在
第五步。更新神秘
模型,使播放器
具有null=False
。
第六步。运行/管理py模式迁移
第7步。运行./manage.py迁移
另一个选项是在添加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添加到Mistery类中,然后再次迁移架构。它将要求数据迁移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.最后运行迁移命令,它将按顺序执行迁移,插入新播放器,并使用对新播放器的引用更新所有Mistery行。
如果您的数据库已经包含神秘对象,那么south必须知道在player
字段中输入了什么值,因为它不能为空。
一种可能的解决办法:
选择吧
2. Specify a one-off value to use for existing columns now
然后输入1。所以你现有的所有神秘对象现在都会指向pk=1的玩家。然后你可以改变(如果需要)这在管理页面。