为什么Django不为我的模型创建外键?

时间:2013-05-13 11:24:43

标签: sql django

我的型号代码如下:

from django.db import models

# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length = 30)
    text = models.CharField(max_length = 150)

class Comment(models.Model):
    text = models.CharField(max_length = 150)
    post = models.ForeignKey(Post)

正在运行

python manage.py sqlall yabe

结果

Mac-mini:yabedjango hn$ python manage.py sqlall yabe
BEGIN;
CREATE TABLE "yabe_post" (
    "id" serial NOT NULL PRIMARY KEY,
    "title" varchar(30) NOT NULL,
    "text" varchar(150) NOT NULL
)
;
CREATE TABLE "yabe_comment" (
    "id" serial NOT NULL PRIMARY KEY,
    "text" varchar(150) NOT NULL
)
;

COMMIT;
Mac-mini:yabedjango hn$

我期待yabe_comment中有一个外键。 Python版本:

Python 2.7.4 (v2.7.4:026ee0057e2d, Apr  6 2013, 11:43:10)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

Django版本:

django-admin.py --version
1.5.1

2 个答案:

答案 0 :(得分:0)

您缺少整个输出。我复制了你的模型并试过了。命令的整个输出: manage.py sqlall app_name是:

BEGIN;
CREATE TABLE `head_post` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `title` varchar(30) NOT NULL,
    `text` varchar(150) NOT NULL
)
;
CREATE TABLE `head_comment` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `text` varchar(150) NOT NULL,
    `post_id` integer NOT NULL
)
;
ALTER TABLE `head_comment` ADD CONSTRAINT `post_id_refs_id_b2b5e564` FOREIGN KEY (`post_id`) REFERENCES `head_post` (`id`);
CREATE INDEX `head_comment_87a49a9a` ON `head_comment` (`post_id`);

COMMIT;

PS。 head是我正在使用的应用名称。

答案 1 :(得分:0)

python manage.py sql yabe

您可以看到"post_id" integer NOT NULL REFERENCES "blog_post" ("id")

BEGIN;
CREATE TABLE "blog_post" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(30) NOT NULL,
    "text" varchar(150) NOT NULL
)
;
CREATE TABLE "blog_comment" (
    "id" integer NOT NULL PRIMARY KEY,
    "text" varchar(150) NOT NULL,
    "post_id" integer NOT NULL REFERENCES "blog_post" ("id")
)
;

我认为它帮助了你