Display Hierarchical Tree (Parent & Child) From Django Self Reference Model

Viewed 232

I am trying to generate a nested/hierarchical structure (categories & sub-categories) that will appear on the Django Admin side.

This is my current model for the Category.

class Category(models.Model):
    name = models.CharField(blank=False, max_length=200)
    slug = models.SlugField(null=False)
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.SET_NULL)

    class Meta:  
        db_table = "dj_categories"
        # Add verbose name
        verbose_name = 'Category'
        verbose_name_plural = "Categories"
        unique_together = ('slug', 'parent',)

    def get_categories(self):
         if self.parent is None:
              return self.name
         else:
             return self.parent.get_categories() + ' -> ' + self.name
    
    def __str__(self):
        return self.get_categories()

This is how my category table looks like.Category table

The above code generate the structure like this in the Django admin panel. Category Layout

Instead I want to achieve the following structure:

Electronics
- Mobile
- Digital Cameras
Fashion
- Men Footwear
-- Casual
Home Appliances
- Washing Machine
- Air Conditioner
-- Windows
-- Split 

Note: I don't want to leverage any third party package such as: Django MPTT or Django Treebeard

A complete example to the problem is highly appreciated.

0 Answers
Related