﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
29854	Altering model primary key might cause referred foreign key attribution inconsistent	Rick Yang	nobody	"Django 1.11.8~16 can reproduce this issue.
DB is MySQL

Reproduced Steps:
1. Create models as following:

{{{
#!python

class TestModel(models.Model):
    filing_no = models.CharField(max_length=16, primary_key=True)


class OtherModel1(models.Model):
    id = models.AutoField(primary_key=True)

    # null=True
    f = models.ForeignKey(TestModel, null=True)


class OtherModel2(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel3(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel4(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel5(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel6(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel7(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel8(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel9(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)


class OtherModel10(models.Model):
    id = models.AutoField(primary_key=True)
    f = models.ForeignKey(TestModel)
}}}

2. Based on above models, we change max_length of TestModel's filing_no and auto-generate migration code as following, and then perform migrating.

{{{
#!python
        migrations.AlterField(
            model_name='testmodel',
            name='filing_no',
            field=models.CharField(max_length=24, primary_key=True, serialize=False),
        ),
}}}

3. Check DB schema of table OtherModel1~10, field f's nullable attribution becomes False, and field f's nullable attribution in some other OtherModel becomes True.


My investigation:

In function BaseDatabaseSchemaEditor._alter_field(), the function call _related_non_m2m_objects(old_field, new_field) will return inconsistent ""old"" and ""new"" related_objects pairs (the model order is different), and generate wrong SQL command to alter foreign keys.
"	Bug	new	Migrations	1.11	Normal		MySQL, Migration, Altering primary key,		Unreviewed	0	0	0	0	0	0
