[Django]-Creating SubCategories with Django Models

18👍

You can create a foreign key to itself:

class Category(models.Model):
   ...
   parent_category = models.ForeignKey('self', null=True, blank=True)

Then you can assigning any existing Category instance as the parent_category of that instance. Then, if you wanted to find all of the subcategories of a given Category instance you would do something like:

subcategories = Category.objects.filter(
    parent_category__id=target_category.id)
👤mVChr

1👍

You can also try django-mptt. It has some additional features.

Leave a comment