Change generated model name without deleting model django

48 Views Asked by At

In django, by default, if you have a structure like this

app
├── migrations
└── models
      └ example

The generated name of your model will be app_example when executing the command makemigrations. My problem is that I want to move my model from the directory app to the directory other_app which has the same structure.

other_app
├── migrations
└── models
    -> example will go here

At the same time, I want the generated name of my model to be other_app_example once I migrate without having to delete my table, as to avoid losing the data in it. The thing is, when you create a migration in django after changing a model of place, django delete the model in the migration directory of app and recreate it in another migration in other_app.

I know that I have to create a custom migration, but how can I achieve what I want to do ? All I found was RenameModel, but it doesn't change the name generated by django.

1

There are 1 best solutions below

0
Lirit On BEST ANSWER

I found a solution, it may not be the best one but it works !

Simply create an empty migration in other_app with the command python manage.py makemigrations --empty other_app.

In it, I added a runSql query where I renamed the table from app_example to other_app_example, like this :

    migrations.RunSQL(
        "ALTER TABLE app_example RENAME TO other_app_example;"
    ),

Before migrating, I just moved my example model to the model directory of other_app, then proceeded to do a python manage.py migrate and it worked fine !

The only downside to this method is that I did not manage to use other methods than raw sql with RunSQL, like RenameField or AlterField did not work for me. I then had to add every changes I wanted to do in raw sql.

Then, to fake the migrations generated by django that delete and create my model, as I couldn't use migrate --fake, I decided to set the managed parameter of my model to be set to false.