In an online shop I use django-mptt
for product categories with several levels. I also have products that each belong to a category.
Now I'd like to visualise the category tree like this:
all(18)
- edible (10)
-- food (4)
-- drink (6)
- inedible (8)
-- wood (3)
-- rock (5)
where the numbers in scopes are the product counts for each category.
I am able to visualize the category tree. I can also place the product count behind the category names, but the way I am doing it seems very inefficient. I basically have a get_number_of_products()
methods at the category model which returns the number of products for a category. But this needs a new database query each time.
One way to deal with this is to use caching as I don't change the product count that often, but I'd prefer a method that needs less database queries to get the tree with the product count.