Django 1.7: Makemigration: non-nullable field

孤者浪人 提交于 2019-12-03 16:30:32

As the order field is unique, you'll need to add the field in several migration steps, replacing the original operations in your migration:

  • Add a nullable field, set the default to NULL.
  • Set the field to a unique value in each row.
  • Add a NOT NULL constraint.

I.e. something like this:

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 is a function that sets the order to a valid value, e.g.:

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()

It's easiest to provide a default value (i.e. 0), and then replace the operations in the generated migration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!