Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Include products from subcategories in category query

Marcin Gębala643f77f14673
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 3de14af47d..1f75ecf3c1 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -40,7 +40,7 @@ def resolve_attributes(info, category_id, query):
def resolve_categories(info, query, level=None):
- qs = models.Category.objects.all()
+ qs = models.Category.objects.prefetch_related('children')
if level is not None:
qs = qs.filter(level=level)
qs = filter_by_query_param(qs, query, CATEGORY_SEARCH_FIELDS)
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index 8ad36f2b17..97239b2e03 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -411,9 +411,16 @@ class Category(CountableDjangoObjectType):
return self.get_absolute_url()
def resolve_products(self, info, **kwargs):
- if hasattr(self, 'prefetched_products'):
+ # If the category has no children, we use the prefetched data.
+ children = self.children.all()
+ if not children and hasattr(self, 'prefetched_products'):
return self.prefetched_products
- qs = self.products.visible_to_user(info.context.user)
+
+ # Otherwise we want to include products from child categories which
+ # requires performing additional logic.
+ tree = self.get_descendants(include_self=True)
+ qs = models.Product.objects.available_products()
+ qs = qs.filter(category__in=tree)
return gql_optimizer.query(qs, info)