'Nested Category In django

how do I use nested categories in django

as Im nwe to django and doing this and find some solutions but didnt work anything

class MainCategory(models.Model):
    name = models.CharField(max_length=50)
    date_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class SubCategory(models.Model):
    perentcategory = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True)
    name = models.CharField(max_length=50)
    date_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class Items(models.Model):
    # maincategory = models.ForeignKey(MainCategory, on_delete=models.CASCADE)
    category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='SubCategory')
    name = models.CharField(max_length=255)

Please share your thoughts



Solution 1:[1]

you may need something like this:

class Category(models.Model):
    name = models.CharField(max_length=50)
    parent = models.ForeignKey(
        'self', null=True, blank=True,
        related_name='children', on_delete=models.CASCADE
    )

    def save(self, *args, **kwargs):
        # prevent a category to be itself parent
        if self.id and self.parent and self.id == self.parent.id:
            self.parent = None
        super().save(*args, **kwargs)

then use it like:

class Product(models.Model):
    # ...
    categories = models.ManyToManyField(
        Category, related_name='products', blank=True
    )

Solution 2:[2]

class Category(models.Model):
   parent_category = models.ForeignKey('self',related_name='child_category_list',on_delete=models.SET_NULL,blank=True,null=True)
   name            = models.CharField(max_length=255)
   path            = models.TextField(null=True,blank=True)


   def __str__(self):
       return self.path

   class Meta:
      verbose_name_plural = "Categories"

def pre_save_parent_category(sender,instance,**kwargs):
   instance.path = instance.name
   parent_category_obj = instance.parent_category
   while parent_category_obj is not None:
      instance.path = parent_category_obj.name + " > " + instance.path
      parent_category_obj = parent_category_obj.parent_category

Solution 3:[3]

class Category(models.Model):
    category_parent=models.ForeignKey('self',on_delete=models.CASCADE,related_name='children',blank=True,null=True)
    category_name=models.CharField(max_length=100)
    slug=models.SlugField(max_length=100,unique=True,)
    description=models.TextField()
    is_active=models.BooleanField(default=True)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

    class Meta:
        ordering=('-created_at',)

    def __str__(self):
        return self.category_name

This might be a better idea for You.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Subham Sharma