Ravi Panchal
Ravi Panchal

Reputation: 1

How to make model for sub-category and category for product in django?

I have to make product model in django where when we select the the main category which is foreign key then we have to select sub category, problem is that it will show the all sub category. it have to show the sub category as per main category selected

Main Category Model

Here we just have three fields

class Category(models.Model):
    image = models.ImageField(upload_to="maincategory",null=True)
    icon = models.CharField(max_length=200,null=True)
    title = models.CharField(max_length=200,null=True)

    def __str__(self):
        return self.title

Sub Category Model

here we give the Main category as foreignkey

class SubCategory(models.Model):
    main_category = models.ForeignKey(Category,on_delete=models.CASCADE)
    title = models.CharField(max_length=200,null=True)

    def __str__(self):
        return self.main_category.title + " - " + self.title

Product Model

In The Product model i will give two foreign key for main and sub category

maincategory = models.ForeignKey(Category,on_delete=models.CASCADE,null=True,blank=True)

subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE,null=True,blank=True)

class Product(models.Model):
    sts = (
        ("PUBLISH","PUBLISH"),
        ("DRAFT","DRAFT"),
    )
    vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE)
    maincategory = models.ForeignKey(Category,on_delete=models.CASCADE,null=True,blank=True)
    subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE,null=True,blank=True)
    title = models.CharField(max_length=200,null=True)
    description = models.TextField()
    price = models.IntegerField(null=True,default=0)
    discount = models.IntegerField(null=True,default=0)
    stock = models.IntegerField(null=True,default=0)
    size = models.CharField(max_length=200,null=True,blank=True)
    color = models.CharField(max_length=200,null=True,blank=True)
    date = models.DateTimeField(auto_now_add=True)
    slug = AutoSlugField(populate_from='title',unique=True,null=True,default=None)
    status = models.CharField(choices=sts,null=True)

    def __str__(self):
        return self.vendor + " - " + self.title
   

So how to create model where select subcategory as per main category in admin panel django

Upvotes: 0

Views: 860

Answers (1)

Onyilimba
Onyilimba

Reputation: 1217

If all you want to do is have a nested subcategories, you can look into django mptt django-mptt

or you can follow this blog post simpleit

there is a category tutorial using django mptt. also you can further customize django mptt to limit it's depth.

Upvotes: 1

Related Questions