[Answered ]-Subcategories Django Shop

2๐Ÿ‘

โœ…

You can add a parent_category field to your Category model which is a foreign key to itself:

parent_category=models.ForeignKey('self', on_delete=models.CASCADE, null=True)

Then you can treat any Category that has a parent_category as a subcategory.

If you want a product to be in more than one (sub)category you will have to make the category field on your Product model a ManyToMany field instead of a Foreign Key. If a product can have at most one category and at most one subcategory then you can leave a category and subcategory field on your Product model but you will have to set a related_name for each.

๐Ÿ‘คvoodoo-burger

0๐Ÿ‘

You can create adjacency tree from Category objects by using this field (as mentioned by voodoo-burger), i also added blank=True, to be able to create root Category in Django admin.

parent=models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)

Next, if you have many categories and want to do queries on your tree structure, you need to look on MPTT (https://github.com/django-mptt/django-mptt).

๐Ÿ‘คDmitry Shilyaev

Leave a comment