Django 1.7:Makemigration:不可空的字段

时间:2015-01-18 16:59:20

标签: python django database field non-nullable

我正在尝试在我的项目中使用django-orderedmodel(https://github.com/kirelagin/django-orderedmodel)。

运行makemigrations不起作用:

 You are trying to add a non-nullable field 'order' to slide without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option: 

我想知道我做错了什么。感谢

1 个答案:

答案 0 :(得分:4)

由于order字段是唯一的,您需要在多个迁移步骤中添加该字段,替换迁移中的原始operations

  • 添加可为空的字段,将默认值设置为NULL
  • 将字段设置为每行中的唯一值。
  • 添加NOT NULL约束。

即。像这样的东西:

operations = [
    migrations.AddField('myapp.MyModel', 'order', models.PositiveIntegerField(null=True, unique=True)),
    migrations.RunPython(set_order),
    migrations.AlterField('myapp.MyModel', 'order', models.PositiveIntegerField(blank=True, unique=True)),
]

其中set_order是将order设置为有效值的函数,例如:

def set_order(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')
    for i, model in enumerate(MyModel.objects.all()):
        model.order = i
        model.save()

最简单的方法是提供默认值(即0),然后替换生成的迁移中的operations

相关问题