About Renaming Fields In Migrations

When you rename a model field including its verbose name, automatic migrations suggest to remove the old field and add a new one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import myproject.apps.myapp.models
from django.db import migrations, models

class Migration(migrations.Migration):
    ...
    operations = [
        migrations.RemoveField(
            model_name="logo",
            name="image",
        ),
        migrations.AddField(
            model_name="logo",
            name="raster_image",
            field=models.ImageField(blank=True, upload_to=myproject.apps.myapp.models.upload_logos_to, verbose_name="Raster Image"),
        ),
    ]

You can manually change that to the rename and alter operations to preserve the data that is already entered:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import myproject.apps.myapp.models
from django.db import migrations, models

class Migration(migrations.Migration):
    ...
    operations = [
        migrations.RenameField(
            model_name="logo",
            old_name="image",
            new_name="raster_image",
        ),
        migrations.AlterField(
            model_name="logo",
            name="raster_image",
            field=models.ImageField(blank=True, upload_to=myproject.apps.myapp.models.upload_logos_to, verbose_name="Raster Image"),
        ),
    ]

Tips and Tricks Programming Architecture Django 4.2 Django 3.2 Django 2.2