【发布时间】:2020-09-16 06:41:12
【问题描述】:
我正在使用 Django 3.0.6
我将ForeignKey 和ManyToManyField 添加到我的模型中,但我注意到django 在db 中创建了INDEX,而不是实际的FOREIGN KEY 约束。
我尝试显式设置db_constraint=True,但正如预期的那样没用,因为它默认为True。
我找到了很多解释这一点的答案,但仅适用于非常旧的 Django 版本,当它被禁用时会使用技巧来启用它。现在,它应该开箱即用。找不到任何关于 Django 3 的ATALL。
代码
class Token (models.Model):
owner = models.ForeignKey(Chiefdom, on_delete=models.CASCADE, db_constraint=True)
county = models.ManyToManyField(County, db_constraint=True)
amount = models.PositiveSmallIntegerField()
SQLite
CREATE TABLE IF NOT EXISTS Piece_token (
id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
amount smallint unsigned NOT NULL,
owner_id integer NOT NULL
);
CREATE INDEX IF NOT EXISTS Piece_token_owner_id_d27c77f0 ON Piece_token (owner_id);
CREATE TABLE IF NOT EXISTS Piece_token_county (
id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
token_id integer NOT NULL,
county_id integer NOT NULL
);
CREATE INDEX IF NOT EXISTS Piece_token_county_county_id_57802417 ON Piece_token_county (county_id);
CREATE INDEX IF NOT EXISTS Piece_token_county_token_id_e7798ae9 ON Piece_token_county (token_id);
CREATE UNIQUE INDEX IF NOT EXISTS Piece_token_county_token_id_county_id_b06b16cc_uniq ON Piece_token_county (token_id, county_id);
【问题讨论】:
-
您必须在 SQLite stackoverflow.com/a/17213720/599023 中显式启用参照完整性实施@
-
@Andee 我很惊讶,因为这些都是非常古老的答案,而较新的答案明确表示“不再需要”。除非它不起作用。
-
这能回答你的问题吗? Does SQLite support referential integrity?
-
@iklinac 不,因为我不知道如何使它在 django 中工作,并且链接的答案不起作用。
-
你用的是什么版本的sqlite
标签: django sqlite foreign-keys