Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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;

Change:

tag_type = models.ForeignKey(Tagtypes, models.DO_NOTHING, db_column='Tag_Type', blank=True, null=True)
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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.