django model去掉unique_together报错的解决方案
事情是这样的,我有一个存储考试的表 class Exam(models.Model): category = cached_fields.ForeignKeyField(Category) name = models.CharField(max_length=128) date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('category','date') category 表示考试的类型, date 表示考试的日期。建表的时候考虑到一个类型的考试在同一个应该只有一个考试,所以就加了一个 用过 django 的人都知道,这不是个大问题,删掉 复制代码 代码如下: django.db.utils.OperationalError: (1553,"Cannot drop index 'insurance_exam_category_id_a430e581_uniq': needed in a foreign key constraint") 数据库不让我删除这个 index ,并且告诉我有一个 外键约束 用到了这个它。我就奇怪了, 没办法,我只能到数据库里寻找答案, | insurance_exam | CREATE TABLE `insurance_exam` ( `id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(128) NOT NULL,`date` date NOT NULL,`created_at` datetime(6) NOT NULL,`updated_at` datetime(6) NOT NULL,`category_id` int(11) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `insurance_exam_category_id_a430e581_uniq` (`category_id`,`date`),CONSTRAINT `insurance_exam_category_id_a2238260_fk_insurance_category_id` FOREIGN KEY (`category_id`) REFERENCES `insurance_category` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1062 DEFAULT CHARSET=utf8mb4 | 可以看到 外键只能是 原因是这样的: 在Mysql中外键会自动在表上添加一个index ,也就说如果没有unique_together,我们的表应该是这样的: | insurance_exam | CREATE TABLE `insurance_exam` ( `id` int(11) NOT NULL AUTO_INCREMENT,KEY `category_id` (`category_id`),CONSTRAINT `insurance_exam_category_id_a2238260_fk_insurance_category_id` FOREIGN KEY (`category_id`) REFERENCES `insurance_category` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1062 DEFAULT CHARSET=utf8mb4 | 但是因为有了 机智的小伙伴应该想到了,如果我们要去掉 alter table exam add index(category_id); 这样,migrate就能成功了。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |