Django migration strategy for renaming a model and relationship fields

后端 未结 12 1615
一个人的身影
一个人的身影 2020-11-28 00:54

I\'m planning to rename several models in an existing Django project where there are many other models that have foreign key relationships to the models I would like to rena

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:47

    I also faced the problem as v.thorey described and found that his approach is very useful but can be condensed into fewer steps which are actually step 5 to 8 as Fiver described without step 1 to 4 except that step 7 needs to be changed as my below step 3. The overall steps are as follow:

    Step 1: Edit the related field names in models.py

    class Bar(models.Model):
        name = models.CharField(unique=True, max_length=32)
        description = models.TextField(null=True, blank=True)
    
    
    class AnotherModel(models.Model):
        bar = models.ForeignKey(Bar)  # <-- changed field name
        is_awesome = models.BooleanField()
    
    
    class YetAnotherModel(models.Model):
        bar = models.ForeignKey(Bar)  # <-- changed field name
        is_ridonkulous = models.BooleanField()
    

    Step 2: Create an empty migration

    python manage.py makemigrations --empty myapp
    

    Step 3: Edit the Migration class in the migration file created in Step 2

    class Migration(migrations.Migration):
    
    dependencies = [
        ('myapp', '0001_initial'), 
    ]
    
    operations = [
        migrations.AlterField(
            model_name='AnotherModel',
            name='foo',
            field=models.IntegerField(),
        ),
        migrations.AlterField(
            model_name='YetAnotherModel',
            name='foo',
            field=models.IntegerField(),
        ),
        migrations.RenameModel('Foo', 'Bar'),
        migrations.AlterField(
            model_name='AnotherModel',
            name='foo',
            field=models.ForeignKey(to='myapp.Bar'),
        ),
        migrations.AlterField(
            model_name='YetAnotherModel',
            name='foo',
            field=models.ForeignKey(to='myapp.Bar'),
        ),
        migrations.RenameField('AnotherModel', 'foo', 'bar'),
        migrations.RenameField('YetAnotherModel', 'foo', 'bar')
    ]
    

    Step 4: Apply the migration

    python manage.py migrate
    

    Done

    P.S. I've tried this approach on Django 1.9

提交回复
热议问题