我正在尝试在我的项目中使用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:
我想知道我做错了什么。感谢
答案 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
。