在postgres中的表格之间创建外键关系

时间:2019-06-04 14:26:28

标签: database postgresql foreign-keys relational-database

我必须使用如下表格:

class BlogCategory(models.Model):
    name = models.CharField(max_length=255)

    class Meta:
        verbose_name = 'Blog category'
        verbose_name_plural = 'Blog categories'

    def __unicode__(self):
        return self.name


class Blog(models.Model):
    category = models.ForeignKey(BlogCategory, related_name="blogs", null=True, blank=True)

我想在Blog和BlogCategory之间建立预定的关键关系。 这是我对postgres的命令:

ALTER TABLE blog_blog ADD CONSTRAINT fk_blog_blogcategory FOREIGN KEY (category_id) REFERENCES blogcategory (name);

我得到一个错误:

ERROR:  column "category_id" referenced in foreign key constraint does not exist

2 个答案:

答案 0 :(得分:1)

在原始命令之前运行此命令:

ALTER TABLE blog_blog ADD COLUMN category_id integer;

答案 1 :(得分:0)

可以尝试:

ALTER TABLE blog_blog ADD CONSTRAINT fk_blog_blogcategory FOREIGN KEY (name) REFERENCES blogcategory (name);