为什么django不会为多对多映射生成约束,如下所示:

时间:2011-11-16 16:28:07

标签: django django-models

问题>为什么django 1.3('ENGINE':'django.db.backends.sqlite3')不对表bookmarks_tag_bookmark的tag_id属性应用约束?

Generated:
    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")
    )
    ;

Expected:
    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")
    )
    ;

    # ----- Detail of The Coding ------------ #
    user@ubuntu:~/Documents/Django/django_bookmarks$ cat bookmarks/models.py
    from django.db import models
    from django.contrib.auth.models import User

    # Create your models here.

    class Link(models.Model):
        url = models.URLField(unique=True)

    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)

    user@ubuntu:~/Documents/Django/django_bookmarks$ python manage.py syncdb
    user@ubuntu:~/Documents/Django/django_bookmarks$ python manage.py sql bookmarks
    BEGIN;
    CREATE TABLE "bookmarks_link" (
        "id" integer NOT NULL PRIMARY KEY,
        "url" varchar(200) NOT NULL UNIQUE
    )
    ;
    CREATE TABLE "bookmarks_bookmark" (
        "id" integer NOT NULL PRIMARY KEY,
        "title" varchar(200) NOT NULL,
        "user_id" integer NOT NULL REFERENCES "auth_user" ("id"),
        "link_id" integer NOT NULL REFERENCES "bookmarks_link" ("id")
    )
    ;
    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")
    )
    ;
    CREATE TABLE "bookmarks_tag" (
        "id" integer NOT NULL PRIMARY KEY,
        "name" varchar(64) NOT NULL UNIQUE
    )
    ;
    COMMIT;
    user@ubuntu:~/Documents/Django/django_bookmarks$

1 个答案:

答案 0 :(得分:5)

由于此时未创建bookmarks_tag,因此无法在创建表时定义约束。但是,如果您执行manage.py sqlall,则会在创建所有表后稍后执​​行ALTER TABLE添加约束。

(虽然值得指出的是,Sqlite除非在最近的版本中忽略了约束,否则只有在特别启用时才会被忽略。)