Django 1.7:Makemigration:不可为空字段

2024-03-09

我正在尝试使用 django-orderedmodel (https://github.com/kirelagin/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: 

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


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在生成的迁移中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django 1.7:Makemigration:不可为空字段 的相关文章

随机推荐