如何使用Django 1.7迁移将现有的django模型迁移到django-ordered-model?

时间:2014-12-26 19:16:13

标签: django django-models django-migrations

我有一个现有的模型,我想用django-ordered-model订购,我之所以选择它是因为它与django.contrib.admin集成在一起。

现在模型按pk排序,我想保留这个排序。当我运行manage.py makemigrations时,它会问我:

You are trying to add a non-nullable field 'orderable' to Item 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

两种选择似乎都错了。我该怎么办?

2 个答案:

答案 0 :(得分:2)

我所做的是回答1,提供值0,然后在迁移文件中添加:

def set_initial_order(apps, schema_editor):
    model = apps.get_model('exercises', 'Item')
    for s in model.objects.all():
        s.order = s.pk
        s.save()

class Migration(migrations.Migration):
    # ...
    operations = [
        migrations.AlterModelOptions(
            # ...
        migrations.AddField(
            # ...
        migrations.RunPython(
            set_initial_order,
            reverse_code=lambda apps, schema_editor: None
        ),
    ]

这意味着对于所有内容,订单最初将为0,但随后将立即更改为等于pk,并且在反向迁移中不需要执行任何操作,因为该列即将被删除。

答案 1 :(得分:0)

如果你有order_with_respect_to设置:

def set_initial_order(apps, schema_editor):
    Lecture = apps.get_model('lectures', 'Lecture')
    Item = apps.get_model('exercises', 'Item')
    for lecture in Lecture.objects.all():
        for index, item in enumerate(Item.objects.filter(lecture=lecture).order_by('id').all()):
            item.order = index
            item.save()


class Migration(migrations.Migration):

    # ...
    operations = [
        migrations.AlterModelOptions(
            # ...
        ),
        migrations.AddField(
            # ...
        ),
        migrations.RunPython(
            set_initial_order,
            reverse_code=lambda apps, schema_editor: None
        ),
    ]