Django isn't creating db constraints for foreign keys with SQLite

故事扮演 提交于 2020-06-01 05:05:52

问题


I'm using Django 3.0.6

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.

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

I've found so many answers explaining this, but only for very old Django versions, doing tricks for enabling it when it was otherwise disabled. Now instead it should just work out of the box. Couldn't find anything AT ALL regarding Django 3.


Code

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

回答1:


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

For example

SELECT * FROM pragma_foreign_key_list('auth_user_groups');

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



来源:https://stackoverflow.com/questions/62073346/django-isnt-creating-db-constraints-for-foreign-keys-with-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!