How to Rename a Model in Django without Loosing Data
Noah Olatoye

Noah Olatoye

867

How to Rename a Model in Django without Loosing Data

When you change a model's name and run python manage.py makemigrations, you will get an autogenerated file in your migration.

We want to rename Contact to ContactList in the Django model. After running the migrations, check the folder for the autogenerated file similar to below.

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('marketing', '0028_sendemail_schedule'),
    ]

    operations = [
        migrations.RenameModel(
            name='LeadContact',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('first_name', models.CharField(max_length=15)),
                ('last_name', models.CharField(max_length=15)),
                ('full_name', models.CharField(blank=True, max_length=50)),
            ],
        ),

You need to do a manual edit. Delete everything inside the operations = [] and replace with the following.

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('marketing', '0028_sendemail_schedule'),
    ]

    operations = [
        migrations.RenameModel('Contact', 'ContactList')
    ]
    atomic = False

For you to run migrate without error, atomic = False is needed. With the atomic false, you tell SQLite not to check the relationship with other tables but perform only the name change.

Now, run the python manage.py migrate. Things should work fine now.

A tech career with instinctHub

Ready to kickstart your tech career or enhance your existing knowledge? Contact us today for a dedicated instructor experience that will accelerate your learning and empower you to excel in the world of technology.

Our expert instructors are here to guide you every step of the way and help you achieve your goals. Don't miss out on this opportunity to unlock your full potential. Get in touch with us now and embark on an exciting journey towards a successful tech career.

Add Comments

First Name
Last Name
Say something:

Are you human? Solve this:

+ = ?

Post you may also like