Opened 7 years ago

Closed 7 years ago

#26404 closed Bug (duplicate)

Change of primary key field does not update foreign keys in migration

Reported by: Maciej Pawlisz Owned by: nobody
Component: Migrations Version: 1.9
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Changing from:

class ModelA(models.Model):
    new_pk = models.IntegerField()


class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA)

To:

class ModelA(models.Model):
    new_pk = models.IntegerField(primary_key=True)


class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA)

Results in migration:

class Migration(migrations.Migration):

    dependencies = [
        ('test_app', '0001_initial'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='modela',
            name='id',
        ),
        migrations.AlterField(
            model_name='modela',
            name='new_pk',
            field=models.IntegerField(primary_key=True, serialize=False),
        ),
    ]

ForeignKey model_a in ModelB is not altered, so table description at least in sqlite is wrong:

CREATE TABLE "test_app_modelb" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "model_a_id" integer NOT NULL REFERENCES "test_app_modela" ("id"))

so connection.check_constraints(['test_app_modelb']) fails with exception

OperationalError: no such column: REFERRED.id

making it impossible to load fixture data.

Manually adding Operation:

        migrations.AlterField(
            model_name='modelb',
            name='model_a',
            field=models.ForeignKey(on_delete=models.deletion.CASCADE, to='test_app.ModelA'),
        )

at the end of migration resolves this problem.

Change History (1)

comment:1 Changed 7 years ago by Tim Graham

Resolution: duplicate
Status: newclosed

Duplicate of #25012

Note: See TracTickets for help on using tickets.
Back to Top