事情是這樣的,我有一個存儲考試的表
1
2
3
4
5
6
7
8
9
|
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
。但是由于業務需要,這個 unique_together
不需要了。
用過 django 的人都知道,這不是個大問題,刪掉 unique_together
的代碼,然后 makemigrations
唄,確實,我就這么做了。但是當我 migrate
的時候卻報錯了,錯誤如下:
數據庫不讓我刪除這個 index ,并且告訴我有一個 外鍵約束 用到了這個它。我就奇怪了,category
是外鍵沒錯,但是我這個是 unique_together
啊,怎么可能有哪個外鍵用到了它呢?
沒辦法,我只能到數據庫里尋找答案, show create table exam
,輸出如下:
1
2
3
4
5
6
7
8
9
10
11
|
| 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,我們的表應該是這樣的:
1
2
3
4
5
6
7
8
9
10
11
|
| 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 在聯合索引的左邊,根據 最左前綴 原則, category 的索引就有了,所以就不會另外建索引,這個時候 category 的外鍵約束就依賴了這個 unique_key ,所以刪除的時候會出現那樣的報錯。
機智的小伙伴應該想到了,如果我們要去掉 unique_together
,我們可以將 category
的 KEY
加回去,這樣就可以將 unique_together
刪掉了。 sql 如下:
1
|
alter table exam add index (category_id); |
這樣,migrate就能成功了。