Categories and sub-categories in django

Viewed 1800

I have an entity of Products, category and sub-category. A category can have many products and also a category can have many sub-categories. For example a product called Iphone-4 can fall on smart phone subcategories of Electronics & Gadgets Category. Similiary samsung product can fall on same smart-phone sub-categories of Electronics&Gadgets Category. How could i show this relation effectively?

Here is what i did

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

    class Meta:
        unique_together = ('parent',)
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

class Product(models.Model):
    token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False)
    category = models.ForeignKey(Category)
    company = models.ForeignKey(Company, related_name="company_product")
    name = models.CharField(max_length=200, null=True)
    model = models.CharField(max_length=100, blank=True, null=True)
    specification = models.TextField(null=True, blank=True)
    price = models.PositiveIntegerField(default=0)

admin.py

class ProductAdmin(admin.ModelAdmin):
    list_select_related = ('category', 'company',)
    class Meta:
        model = Product

class CategoryAdmin(admin.ModelAdmin):
    list_select_related = ('parent',)
    list_display = ('name', 'parent', )
    class Meta:
        model = Category

This way in my admin, the categories and sub-categories are shown so vaguely. Category Electronics & Gadgets is shown multiple times. It is shown as per the number of sub-category that falls under this category. Is this expected behavior or has to handle this other effective way?

enter image description here

1 Answers

Here is the code snippet to list nested Category and Sub-Category inside the Admin Panel. Please register the Category model in the admin.py of your application first.

# Category Model.
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 __str__(self):
        return self.name
Related