0

我有一个现有的模型,我想让它可以订购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

这两种选择似乎都是错误的。我应该怎么办?

4

2 回答 2

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
        ),
    ]

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

于 2014-12-26T19:16:12.817 回答
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
        ),
    ]
于 2017-04-04T21:54:05.390 回答