[Django]-How to change model class name without losing data?

3👍

If you just go ahead and change the model name in your models.py file, the “makemigrations” command is usually smart enough to pick it up. It will ask you if you changed the model name and create a migration to rename the table accordingly if you confirm.

2👍

Usually in most cases, django makemigrations handles renaming of models on its own but if it doesn’t and creates it as delete and addition of new model, you may have to manually add migrations.RenameModel in your migration file. Django Rename Model

2👍

The two suggested replies did not answer my case.

If you want to go from :

class OldClassName(models.Model):
    class meta:
        db_table = 'unchanged_table_name'

to :

class NewClassName(models.Model):
    class meta:
        db_table = 'unchanged_table_name'

Without having django understanding in migrations "I can see you deleted a model and want me to create a new one"

Here is how I went :

  • in the first migration where your model appears (‘migration.CreateModel’), update it for "name=’NewClassName’"
  • then, in all the other migrations since this one, update "model_name=’newclassname’" where it concerns this specific Model
  • don’t forget also the refereneces to this model in other ‘AddField(ForeignKey)’

If its the only change, you don’t even have to run makemigrations, Django should simply see nothing.

Leave a comment