Django没有使用SQLite为外键创建数据库约束

Django没有使用SQLite为外键创建数据库约束

本文介绍了Django没有使用SQLite为外键创建数据库约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 3.0.6

I'm using Django 3.0.6

我在模型中添加了ForeignKeyManyToManyField,但是我注意到django创建了INDEX,但并未在数据库中创建实际的FOREIGN KEY约束.

I'm adding ForeignKey and ManyToManyField to my models, but I've noticed that django creates the INDEX, but not the actual FOREIGN KEY constraints in the db.

我尝试显式设置db_constraint=True,但是按预期没有用,因为默认情况下为True.

I've tried to explicitly set db_constraint=True but as expected is useless, since it's True by default.

我已经找到了很多答案来解释这一点,但是仅对于非常老的Django版本,就做了一些技巧来使它在其他情况下被禁用.现在,它应该开箱即用.找不到有关Django 3的所有内容.

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

推荐答案

我现在检查了相同版本的Django和SQLite是否存在所有外键

I have checked now with same version of Django and SQLite there are all foreign keys present

例如

SELECT * FROM pragma_foreign_key_list('auth_user_groups');

请注意,所有外键均已从Django推迟并检查-> 来源

Note all foreign keys are deferred and checked from Django -> source

这篇关于Django没有使用SQLite为外键创建数据库约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:29