0

I have an existing model and I want to make it orderable with django-ordered-model, which I chose because it is integrated with django.contrib.admin.

Right now the model is ordered by pk, and I'd like to preserve that ordering. When I run manage.py makemigrations it asks me:

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

Both options seem wrong. What should I do?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Aur Saraf
  • 3,214
  • 1
  • 26
  • 15

2 Answers2

2

What I did was answer 1, provide the value 0, then in the migration file add:

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

This means the order will initially be 0 for everything, but then immediately will be changed to be equal to pk, and in the reverse migration nothing needs to be done because the column is just about to be deleted.

Aur Saraf
  • 3,214
  • 1
  • 26
  • 15
0

If you have order_with_respect_to setup:

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
        ),
    ]
Balazs Nemeth
  • 2,333
  • 19
  • 29