【问题标题】:How to migrate an existing django model to django-ordered-model with Django 1.7 migrations?如何使用 Django 1.7 迁移将现有的 django 模型迁移到 django-ordered-model?
【发布时间】:2014-12-26 19:16:12
【问题描述】:

我有一个现有模型,我想通过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

这两个选项似乎都错了。我该怎么办?

【问题讨论】:

  • 有足够财富的人可以创建并添加标签 django-ordered-model 吗?

标签: django django-models django-migrations


【解决方案1】:

我所做的是回答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,并且在反向迁移中无需执行任何操作,因为该列即将被删除。

【讨论】:

    【解决方案2】:

    如果你有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
            ),
        ]
    

    【讨论】:

      猜你喜欢
      • 2014-12-13
      • 2014-05-28
      • 2015-02-13
      • 2015-03-05
      • 2014-12-21
      • 2015-10-31
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多