MarcS82
MarcS82

Reputation: 2517

'Cannot add foreign key constraint' in django migration

I try to add a 1:n reltationship but the foreign key constraint could not be added.

class PlatformEnv(models.Model):
    id = models.AutoField(db_column='ID', primary_key=True)
    tag_type = models.ForeignKey(Tagtypes, models.DO_NOTHING, db_column='Tag_Type', blank=True, null=True)

class Tagtypes(models.Model):
   name = models.CharField(max_length=50, blank=True, null=True)

This is the generated migration:

migrations.AddField(
    model_name='platformenv',
    name='tag_type',
    field=models.ForeignKey(blank=True, db_column='Tag_Type', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='polls.Tagtypes'),
),

The DB shows the following error:

Error in foreign key constraint of table adtech_mandators/#sql-5de0_4cf61_130:
 FOREIGN KEY (`Tag_Type`) REFERENCES `TagTypes` (`id`):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.

The tables:

CREATE TABLE `TagTypes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

CREATE TABLE `PlatformEnv` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Tag_Type` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`),
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;

Upvotes: 1

Views: 915

Answers (1)

Daniel Holmes
Daniel Holmes

Reputation: 2002

Change:

tag_type = models.ForeignKey(Tagtypes, models.DO_NOTHING, db_column='Tag_Type', blank=True, null=True)

To:

tag_type = models.ForeignKey(Tagtypes, models.DO_NOTHING, blank=True, null=True)

As the error says:

Error in foreign key constraint of table adtech_mandators/#sql-5de0_4cf61_130: FOREIGN KEY (Tag_Type) REFERENCES TagTypes (id):

You are trying to reference a column named Tag_Type which does not exist. Correct name is TagTypes which is the default and does not need to be specified in your foreign key options.

Upvotes: 2

Related Questions