Skip to content

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

Display subcategory products in parent category view

Adam Janik283f0c0c2404
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 3183728d8e..4f7e6e429b 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -113,8 +113,11 @@ def category_index(request, path, category_id):
if actual_path != path:
return redirect('product:category', permanent=True, path=actual_path,
category_id=category_id)
+ # Check for subcategories
+ categories = category.get_descendants(include_self=True)
+ ids = [c.id for c in categories]
products = products_with_details(user=request.user).filter(
- category__id=category.id).order_by('name')
+ category__id__in=ids).order_by('name')
product_filter = ProductCategoryFilter(
request.GET, queryset=products, category=category)
ctx = get_product_list_context(request, product_filter)
diff --git a/tests/conftest.py b/tests/conftest.py
index 027a0c1797..f2f592fd88 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -642,3 +642,16 @@ def closed_orders(billing_address):
def collection(db):
collection = Collection.objects.create(name='Collection', slug='collection')
return collection
+
+
+def product(product_type, default_category):
+ product_attr = product_type.product_attributes.first()
+ attr_value = product_attr.values.first()
+ attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
+
+ product = Product.objects.create(
+ name='Test product 1', price=Decimal('10.00'),
+ product_type=product_type, attributes=attributes, is_published=True,
+ category=default_category)
+ return product
diff --git a/tests/test_product.py b/tests/test_product.py
index a8525735b1..8d4e7c3f4b 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -11,6 +11,7 @@ from saleor.cart import CartStatus, utils
from saleor.cart.models import Cart
from saleor.product import (
ProductAvailabilityStatus, VariantAvailabilityStatus, models)
+from saleor.product.models import Category
from saleor.product.utils import (
allocate_stock, deallocate_stock, decrease_stock,
get_attributes_display_map, get_availability,
@@ -515,3 +516,18 @@ def test_render_product_page_with_no_variant(
kwargs={'product_id': product.pk, 'slug': product.get_slug()})
response = admin_client.get(url)
assert response.status_code == 200
+
+
+def test_include_products_from_subcategories_in_main_view(
+ default_category, product, authorized_client):
+ subcategory = Category.objects.create(
+ name='sub', slug='test', parent=default_category)
+ product.category = subcategory
+ product.save()
+ path = default_category.get_full_path()
+ # URL to parent category view
+ url = reverse(
+ 'product:category', kwargs={
+ 'path': path, 'category_id': default_category.pk})
+ response = authorized_client.get(url)
+ assert product in response.context_data['products'][0]