Kimmo Hintikka
Kimmo Hintikka

Reputation: 15520

Why to use 'self' foreignkey in Django Models?

I've seen this pattern many times but I am not sure why people use it and would like to learn.

Here is small copy paste on what I mean: Category class is a blog post category which has the foreign key relationship to self. What do I gain for having such a relationship?

class Category(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField(max_length=32)
    parent = models.ForeignKey('self', blank=True, null=True)

Here is the post entry for the same model. Here I find it obvious you would want to have entry category as key or user if this blog had user system.

class Entry(models.Model):
    title = models.CharField(max_length=64)
    slug = models.SlugField(max_length=32, default='', blank=True)
    created = models.DateTimeField(auto_now=True)
    updated = models.DateTimeField(auto_now=True)
    content = models.TextField()
    category = models.ForeignKey(Category)

Upvotes: 3

Views: 2461

Answers (1)

Muneer Muhammed
Muneer Muhammed

Reputation: 953

Here by using foreign key relationship to self you can have a hierarchical structure for your categories. Like parent categories and subcategories. In previous versions it was TreeForeignKey.

Upvotes: 1

Related Questions