Thom
Thom

Reputation: 1623

Django renaming model field without ALTER TABLE on the database

I'm trying to rename a model field name without any impact on the DB using db_colum.

My model before:

class Foo(models.Model)::
    old_name = models.CharField()

My model after:

class Foo(models.Model)::
    new_name = models.CharField(db_column="old_name")

I generated a migration and Django guessed that I have renamed the field. The migration looks like:

class Migration(migrations.Migration):

    dependencies = [
        ("fooapp", "0001_bar"),
    ]

    operations = [
        migrations.RenameField(
            model_name="foo", old_name="old_name", new_name="new_name",
        ),
        migrations.AlterField(
            model_name="foo",
            name="new_name",
            field=models.CharField(db_column="old_name"),
        ),
    ]

Everything is working fine. I try the migration and it is ok. But if I take a look at the SQL generated (with ./manage.py sqlmigrate), I see:

--
-- Rename field old_name on foo to new_name
--
ALTER TABLE "fooapp_foo" RENAME COLUMN "old_name" TO "new_name";
--
-- Alter field new_name on foo
--
ALTER TABLE "fooapp_foo" RENAME COLUMN "new_name" TO "old_name";

I don't get why the migration does that instead of doing nothing. Is there a way to avoid that?

Upvotes: 2

Views: 1489

Answers (1)

iklinac
iklinac

Reputation: 15738

It does seem that Django migration engine has produced unnecessary migration commands/steps ( should be reported as Bug )

In meantime you could edit migration to avoid these queries from being executed by making custom RunSQL replacement for these migration operations

Something in a line of

migrations.RunSQL(
    migrations.RunSQL.noop,
    state_operations=[
        migrations.RenameField(
            model_name="foo", old_name="old_name", new_name="new_name",
        ),
        migrations.AlterField(
            model_name="foo",
            name="new_name",
            field=models.CharField(db_column="old_name"),
        ),
    ],
)

Upvotes: 2

Related Questions