Say, I've got a product instance. Product instance linked to 4th level child category. If I only want to get root category and 4th level child category the query below is enough to fetch data with minimum database queries:
Product.objects.filter(active=True).prefetch_related('category__root',
'category')
If I have to reach parents of this product's category and using get_ancestors()
method for this, nearly three times mode database query happening.
If I write query like below instead using get_ancestors()
method, database queries stays low.
Product.objects.filter(active=True).prefetch_related(
'category__root',
'category',
'category__parent',
'category__parent__parent',
'category__parent__parent__parent',
'category__parent__parent__parent__parent')
But this query is not effective when level of depth is unknown. Is there a way to prefetch parents dynamically in the query above?