18👍
✅
You can create a foreign key to itself:
class Category(models.Model):
...
parent_category = models.ForeignKey('self', null=True, blank=True)
Then you can assigning any existing Category
instance as the parent_category
of that instance. Then, if you wanted to find all of the subcategories of a given Category
instance you would do something like:
subcategories = Category.objects.filter(
parent_category__id=target_category.id)
- [Django]-Django global name 'PageNotAnInteger' is not defined
- [Django]-NameError: name 'RegexValidator' is not defined
- [Django]-Convert python object to protocol buffer object
- [Django]-Django — Generate form based on queryset
Source:stackexchange.com