As the order
字段是唯一的,您需要在几个迁移步骤中添加该字段,替换原始字段operations
在您的迁移中:
- 添加可为空的字段,将默认值设置为
NULL
.
- 将字段设置为每行中的唯一值。
- Add a
NOT NULL
约束。
IE。像这样的东西:
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)),
]
where 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
在生成的迁移中。