首页 > 解决方案 > 在 postgres 中的表之间创建外键关系

问题描述

我必须如下表:

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

标签: databasepostgresqlforeign-keysrelational-database

解决方案


在原始命令之前运行它:

ALTER TABLE blog_blog ADD COLUMN category_id integer;

推荐阅读