国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

django model去掉unique_together報錯的解決方案

2020-01-04 17:23:03
字體:
來源:轉載
供稿:網(wǎng)友

事情是這樣的,我有一個存儲考試的表

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 表示考試的日期。建表的時候考慮到一個類型的考試在同一個應該只有一個考試,所以就加了一個 unique_together 。但是由于業(yè)務需要,這個 unique_together 不需要了。

用過 django 的人都知道,這不是個大問題,刪掉 unique_together 的代碼,然后 makemigrations 唄,確實,我就這么做了。但是當我 migrate 的時候卻報錯了,錯誤如下:

 

復制代碼 代碼如下:
django.db.utils.OperationalError: (1553, "Cannot drop index 'insurance_exam_category_id_a430e581_uniq': needed in a foreign key constraint")

 

數(shù)據(jù)庫不讓我刪除這個 index ,并且告訴我有一個 外鍵約束 用到了這個它。我就奇怪了,category是外鍵沒錯,但是我這個是 unique_together 啊,怎么可能有哪個外鍵用到了它呢?

沒辦法,我只能到數(shù)據(jù)庫里尋找答案, show create table exam ,輸出如下:

| 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 |

可以看到 UNIQUE KEY 那一行就是 unique_together ,下面一行是 category 外鍵。沒有其他東西了啊,到底哪個外鍵用到了我們的 unique_together

外鍵只能是 category 了,也沒有別的外鍵啊。到底是怎么回事呢?

原因是這樣的: 在Mysql中外鍵會自動在表上添加一個index ,也就說如果沒有unique_together,我們的表應該是這樣的:

| 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`), 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 |

但是因為有了 unique_together unique_key ,并且 category 在聯(lián)合索引的左邊,根據(jù) 最左前綴 原則, category 的索引就有了,所以就不會另外建索引,這個時候 category 的外鍵約束就依賴了這個 unique_key ,所以刪除的時候會出現(xiàn)那樣的報錯。

機智的小伙伴應該想到了,如果我們要去掉 unique_together ,我們可以將 category KEY 加回去,這樣就可以將 unique_together 刪掉了。 sql 如下:

alter table exam add index(category_id);

這樣,migrate就能成功了。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 衡阳市| 安阳市| 通城县| 三门峡市| 宁城县| 晋城| 遂川县| 东城区| 云梦县| 昭苏县| 岳阳市| 泰安市| 佛冈县| 蕲春县| 津南区| 兴安县| 莫力| 平利县| 桐柏县| 正蓝旗| 榆中县| 通榆县| 拜城县| 兴化市| 临湘市| 黄山市| 成武县| 西峡县| 铜川市| 景谷| 珠海市| 呈贡县| 陕西省| 南漳县| 胶州市| 高淳县| 深泽县| 阳信县| 海南省| 道真| 丹江口市|