gpt4 book ai didi

python - Django 1.7 : Makemigration: non-nullable field

转载 作者:太空狗 更新时间:2023-10-30 03:00:48 25 4
gpt4 key购买 nike

我正在尝试在我的项目中使用 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:

我想知道我哪里做错了。谢谢

最佳答案

由于 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

关于python - Django 1.7 : Makemigration: non-nullable field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28012340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com