I have 2 models, Category and Products
class Product(Meta):
categories = models.ManyToManyField(Category, related_name='products')
class Category(Meta):
parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE)
When a user select a Category I need to show all the products in that category including all product of his children and grandchildren etc.
The Category has a FK to itself, so the number of depth levels theoretically is infinite so I need to extract all product from any category below parent depth.
I tried something recursive on the Model(traverse the tree, including parent):
def get_descendants(self, tree=None):
if tree is None:
tree = []
tree.append(self)
for child in self.category_set.all():
return self.get_descendants(child)
return tree
and call in get_object
obj = super().get_object()
Product.objects.filter(categories__in=obj.get_descendants())
I get the following error:
Product.objects.filter(categories__in=obj.get_descendants())
The tree is adding/appending the first category, parent, but gives the error after recursion call on the second append.