user9192656
user9192656

Reputation: 579

Create foreign key relation between tabels in postgres

I have to tables like below:

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)

I would like to create foregin key relation between Blog and BlogCategory. Here is my command for postgres:

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

and i got an error:

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

Upvotes: 0

Views: 130

Answers (2)

Tiger_Mike
Tiger_Mike

Reputation: 146

Run this before your original command:

ALTER TABLE blog_blog ADD COLUMN category_id integer;

Upvotes: 1

Hippolyte BRINGER
Hippolyte BRINGER

Reputation: 863

May be try this :

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

Upvotes: 0

Related Questions