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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With