Skip to content

Instantly share code, notes, and snippets.

@Kobold
Created December 11, 2014 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kobold/e6d4606939ba4cd6ba8d to your computer and use it in GitHub Desktop.
Save Kobold/e6d4606939ba4cd6ba8d to your computer and use it in GitHub Desktop.
How to make an order_with_respect_to migration work.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class AlterOrderWithRespectTo(migrations.AlterOrderWithRespectTo):
"""
Represents a change with the order_with_respect_to option.
"""
def database_forwards(self, app_label, schema_editor, from_state, to_state):
from_model = from_state.render().get_model(app_label, self.name)
to_model = to_state.render().get_model(app_label, self.name)
if self.allowed_to_migrate(schema_editor.connection.alias, to_model):
# Remove a field if we need to
if from_model._meta.order_with_respect_to and not to_model._meta.order_with_respect_to:
schema_editor.remove_field(from_model, from_model._meta.get_field_by_name("_order")[0])
# Add a field if we need to (altering the column is untouched as
# it's likely a rename)
elif to_model._meta.order_with_respect_to and not from_model._meta.order_with_respect_to:
field = to_model._meta.get_field_by_name("_order")[0]
field.default = 1 # !!! Added this so that no null fields are created.
schema_editor.add_field(
from_model,
field,
)
class Migration(migrations.Migration):
dependencies = [
('listingapp', '0004_auto_20141112_1744'),
]
operations = [
AlterOrderWithRespectTo(
name='listitem',
order_with_respect_to='list',
),
]

When I added order_with_respect_to Meta option to my model in Django 1.7, the migrations barfed. Typical makemigrations then migrate and then I got this error: django.db.utils.IntegrityError: column "_order" contains null values

Shit. After hunting around I decided to just modify how the migration was done. I subclassed the AlterOrderWithRespectTo migration and overrode the database_forwards method. It's entirely copy-paste except for line 23. The new field created in lines 22-27 is not-null but no default is provided. Barf. I added line 23 and set a default at least for the migration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment