cgw*_*wid 4 python database django 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:
Run Code Online (Sandbox Code Playgroud)
我想知道我在哪里做错了。谢谢
由于该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)),
]
Run Code Online (Sandbox Code Playgroud)
whereset_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()
Run Code Online (Sandbox Code Playgroud)
最简单的方法是提供一个默认值(即0),然后operations在生成的迁移中替换。
| 归档时间: |
|
| 查看次数: |
8394 次 |
| 最近记录: |