0
votes

I want to rename a model in Django 3.2, keep my existing migrations and be able to both migrate a db with the old table name and create a db from scratch.

I've started by renaming the model class and all references to it in the code. As "./manage.py makemigrations" did not automatically create a migration, I manually created a migration that renames the model:

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('market_integrations', '0003_migration'),
    ]

    operations = [
        migrations.RenameModel('OldModelName', 'NewModelname')
    ]

My initial idea is that I should not update existing migrations, as I never do when creating other migrations. However, the references to the old model in the old migrations cause a LookupError when I run "./manage.py migrate". I've tried using both the model name string and apps.get_model(). Migration code samples that break:

operations = [
    migrations.CreateModel(
        name="OldModelName",
    ...
    )
]


operations = [
    migrations.CreateModel(
        name=apps.get_model("myapp", "OldModelName"),
    ...
    )
]

As keeping the old model name in old migrations didn't work, I replaced the old model name in old migrations with the new name. "./manage.py migrate" ran successfully, including the model renaming migration. However, when I try to create a new database, the model renaming migration fails because that new database never had a table with the old name.

What should I do to be able to preserve my migrations and have them working in both existing and new databases?

I have already checked Django migration strategy for renaming a model and relationship fields , but I didn't find the answer to my question there.