在postgres中创建表之间的外键关系
Create foreign key relation between tabels in 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
可以试试这个:
ALTER TABLE blog_blog ADD CONSTRAINT fk_blog_blogcategory FOREIGN KEY (name) REFERENCES blogcategory (name);
运行 在您的原始命令之前:
ALTER TABLE blog_blog ADD COLUMN category_id integer;
我必须像下面这样的表格:
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
可以试试这个:
ALTER TABLE blog_blog ADD CONSTRAINT fk_blog_blogcategory FOREIGN KEY (name) REFERENCES blogcategory (name);
运行 在您的原始命令之前:
ALTER TABLE blog_blog ADD COLUMN category_id integer;