开发者

How can I make a join table with Django models?

I'm a beginner bumbling through a Django guide and it told me to put this in 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)

This should make a join table with this 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")
);

But when I run manage.py sql bookmarks, I instead get this 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")
);

The join table doesn't reference the tag table. Could anyone please explain to me what is wrong?


Look further down the output of ./manage.py sql. I suspect you'll see a line like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜