编程语言
首页 > 编程语言> > python – Django 1.7:Makemigration:不可空的字段

python – Django 1.7:Makemigration:不可空的字段

作者:互联网

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

我想知道我在做错了什么.谢谢

解决方法:

由于订单字段是唯一的,您需要在几个迁移步骤中添加该字段,替换迁移中的原始操作:

>添加可为空的字段,将默认值设置为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是一个将顺序设置为有效值的函数,例如:

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),然后替换生成的迁移中的操作.

标签:python,database,field,django,non-nullable
来源: https://codeday.me/bug/20190624/1275867.html