Another solution maybe a bit easier and that can be deployed by itself during the migration.
Let's consider the old app old_app
and the renamed one new_app
.
- The first step is to retrieve the SQL commands to create the models in case the
new_app
is deployed on a fresh database (you might need to merge the migration of the old app to get a single migration file):
python3 ./manage.py sqlmigrate old_app 0001_initial
--
-- Create model MailingList
--
CREATE TABLE `old_mailinglist` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `email` varchar(254) NOT NULL);
- The second step is to create a new migration file in the new app
python3 ./manage.py makemigrations new_app --empty --name rename_app
- In this new migration file, copy and adapt this code:
# -*- coding: utf-8 -*-
from django.db import connections, migrations
def create_or_update_mailing_list(apps, schema_editor):
db_alias = schema_editor.connection.alias
try:
_ = apps.get_model("old_app", "MailingList")
print("Rename table MailingList app")
with connections[db_alias].cursor() as cursor:
cursor.execute("UPDATE django_content_type SET app_label=new_app WHERE app_label=old_app;")
cursor.execute("ALTER TABLE old_app_mailinglist RENAME TO new_app_mailinglist;")
except LookupError:
print("Create table MailingList")
with connections[db_alias].cursor() as cursor:
cursor.execute("CREATE TABLE `new_app_mailinglist` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `email` varchar(254) NOT NULL);")
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.RunPython(create_or_update_mailing_list),
]