Opened 7 years ago

Closed 7 years ago

#25752 closed Bug (duplicate)

RenameField on m2m causes error when new m2m field is added with old name

Reported by: skyjur Owned by: nobody
Component: Migrations Version: 1.7
Severity: Normal Keywords: postgres migrations renamefield
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by skyjur)

Given I have a field

   many = ManyToManyField()

I create a migration:

   RenameField: "many" to "many_legacy"
   Create Field: "many" as ManyToManyField()

When I run the migration I get:

...
  File "django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "cms_test_many_2e06cda4" already exists

It seems the problem is that RenameField does not rename database indexes, and then when new m2m field is being added it tries to create index with same name and so I get database error.

Here is full migration code which throws this error:

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RenameField(
            'test',
            'many',
            'many_legacy',
        ),
        migrations.AddField(
            model_name='test',
            name='many',
            field=models.ManyToManyField(to='cms.NewRel2'),
        ),
    ]

Initially I noticed this error on 1.7, then I also managed to replicate it on 1.8

Error happened on postgres database.

Change History (7)

comment:1 Changed 7 years ago by skyjur

comment:2 Changed 7 years ago by skyjur

Type: UncategorizedBug

comment:3 Changed 7 years ago by skyjur

Description: modified (diff)

comment:4 Changed 7 years ago by skyjur

The workaround I used was to rename those sql indexes with additional RunSQL:

    migrations.RunSQL(
        'alter table cms_test_many_2e06cda4 rename to cms_test_many_legacy_2e06cda4',
        'alter table cms_test_many__legacy_2e06cda4 rename to cms_test_many_2e06cda4'
    )

comment:5 Changed 7 years ago by skyjur

Version: 1.81.7

comment:6 Changed 7 years ago by Tim Graham

Could it be a duplicate of #23577?

comment:7 Changed 7 years ago by Tim Graham

Resolution: duplicate
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top