Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add nested categories to a Django model?

What I am trying to achieve is to design a model which has nested levels of categories.

the levels are like this.

category0 > category1 > category2 > category3 > category4 > category5

Posts can have levels from 0 - 5, so a post can have category 0 - 1, while other post may have0 - 4 or 0 - 5,

The category on the given highest level (0 is the lower while 5 is the highest) should inherit from the one just below it, (1 > 2 > 3 > 4 > 5)

How can I achive this?

My current categories looks like this

class Category0(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=60)


class Category1(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=60)
    parent = models.ForeignKey(Category0)


class Category2(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=60)
    parent = models.ForeignKey(Category1)


class Category3(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=60)
    parent = models.ForeignKey(Category2)


class Category4(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=60)
    parent = models.ForeignKey(Category3)


class Category5(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=60)
    parent = models.ForeignKey(Category4)

And the post model here

class Product(models.Model):
    title = models.CharField(max_length=20)
    slug = AutoSlugField(unique=True, populate_from='title')
    content = models.TextField(blank=True)
    category = models.ForeignKey(CategoryChild4)

What would be the best method? any suggestions or changes welcome.

Update

The backend is PostgrSQL.

Thanks

like image 540
All Іѕ Vаиітy Avatar asked Sep 17 '15 20:09

All Іѕ Vаиітy


1 Answers

Could you use a Foreign Key to self approach?

For example:

class Category(models.Model):

    parent = models.ForeignKey('self', default=None, null=True, blank=True, related_name='nested_category')
    nesting_level = models.IntegerField()
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=60)

It's probably useful to keep track of the nesting levels explicitly with nesting_level but this way you can create the relationship you describe.

like image 66
djq Avatar answered Nov 04 '22 15:11

djq