如何使用Django模型创建连接表?

时间:2011-09-16 21:31:12

标签: database django django-models

我是一个初学者,在Django指南中笨手笨脚,它告诉我把它放在models.py中:

class Bookmark(models.Model):
    title = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    link = models.ForeignKey(Link)

class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)
    bookmarks = models.ManyToManyField(Bookmark)

这应该与这个SQL形成一个连接表:

CREATE TABLE "bookmarks_tag_bookmarks" (
    "id" integer NOT NULL PRIMARY KEY,
    "tag_id" integer NOT NULL REFERENCES "bookmarks_tag" ("id"),
    "bookmark_id" integer NOT NULL REFERENCES "bookmarks_bookmark" ("id"),
    UNIQUE ("tag_id", "bookmark_id")
);

但是当我运行manage.py sql书签时,我得到了这个SQL:

 CREATE TABLE "bookmarks_tag_bookmarks" (
    "id" integer NOT NULL PRIMARY KEY,
    "tag_id" integer NOT NULL,
    "bookmark_id" integer NOT NULL REFERENCES "bookmarks_bookmark" ("id"),
    UNIQUE ("tag_id", "bookmark_id")
);

连接表不引用标记表。有人可以向我解释有什么问题吗?

1 个答案:

答案 0 :(得分:1)

进一步查看./manage.py sql的输出。我怀疑你会看到一句话:

ALTER TABLE "bookmarks_tag_bookmarks" ADD CONSTRAINT "tag_id_refs_id_somehash" FOREIGN KEY ("tag_id") REFERENCES "bookmarks_bookmark" ("id") DEFERRABLE INITIALLY DEFERRED;