4

我正在阅读 Django 教程并定义投票和选择模型。当我运行manage.py sql polls查看 sql 语句时,我得到:

CREATE TABLE `polls_poll` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `question` varchar(200) NOT NULL,
    `pub_date` datetime NOT NULL
);

CREATE TABLE `polls_choice` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `poll_id` integer NOT NULL,
    `choice_text` varchar(200) NOT NULL,
    `votes` integer NOT NULL
);

ALTER TABLE `polls_choice` ADD CONSTRAINT `poll_id_refs_id_3aa09835`
    FOREIGN KEY (`poll_id`) REFERENCES `polls_poll` (`id`);

为什么DjangoALTER在应用外键时使用语句而不是在Create table语句中执行?类似以下的内容似乎更简洁:

`poll_id integer NOT NULL REFERENCES polls_choice(id)`
4

1 回答 1

5

避免依赖问题和循环引用。例如,假设有两个表:

CREATE TABLE parent ( id, first_child_id );
CREATE TABLE child ( id, parent_id );

必须在定义表之后添加parent和之间的至少一个引用。child

现在,因为 MySQL 对引用完整性不是特别小心,所以这不是问题:

mysql> CREATE TABLE parent ( id INTEGER PRIMARY KEY, first_child_id INTEGER NOT NULL REFERENCES child(id) );
Query OK, 0 rows affected (0.00 sec)

但是更迂腐的数据库引擎会抱怨:

test=# BEGIN;
BEGIN
test=# SET CONSTRAINTS ALL DEFERRED;
SET CONSTRAINTS
test=# CREATE TABLE parent (id INTEGER PRIMARY KEY, first_child_id INTEGER NOT NULL REFERENCES child(id));
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "parent_pkey" for table "parent"
ERROR:  relation "child" does not exist
于 2013-04-09T21:19:01.623 回答