Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Filter by categories and collections in products resolver
Marcin Gębalac743f9af3aa0
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex ea760d1086..c6a047a6db 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -43,6 +43,17 @@ def filter_products_by_price(qs, price_lte=None, price_gte=None):return qs+def filter_products_by_categories(qs, categories):+ categories = [+ category.get_descendants(include_self=True) for category in categories]+ ids = set([category.id for tree in categories for category in tree])+ return qs.filter(category__in=ids)+++def filter_products_by_collections(qs, collections):+ return qs.filter(collections__in=collections)++def sort_qs(qs, sort_by):if sort_by:qs = qs.order_by(sort_by)diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex 849bbe023a..3de14af47d 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -4,10 +4,12 @@ from django.db.models import Sum, Qfrom ...order import OrderStatusfrom ...product import models-from ..utils import filter_by_query_param, filter_by_period, get_database_id+from ..utils import (+ filter_by_query_param, filter_by_period, get_database_id, get_nodes)from .filters import (- filter_products_by_attributes, filter_products_by_price, sort_qs)-from .types import Category, ProductVariant, StockAvailability+ filter_products_by_attributes, filter_products_by_categories,+ filter_products_by_collections, filter_products_by_price, sort_qs)+from .types import Category, Collection, ProductVariant, StockAvailabilityPRODUCT_SEARCH_FIELDS = ('name', 'description', 'category__name')CATEGORY_SEARCH_FIELDS = ('name', 'slug', 'description', 'parent__name')@@ -53,8 +55,10 @@ def resolve_collections(info, query):def resolve_products(- info, attributes=None, category=None, stock_availability=None,- query=None, price_lte=None, price_gte=None, sort_by=None):+ info, attributes=None, categories=None, collections=None,+ price_lte=None, price_gte=None, sort_by=None, stock_availability=None,+ query=None, **kwargs):+user = info.context.userqs = models.Product.objects.visible_to_user(user)qs = filter_by_query_param(qs, query, PRODUCT_SEARCH_FIELDS)@@ -62,12 +66,13 @@ def resolve_products(if attributes:qs = filter_products_by_attributes(qs, attributes)- if category is not None:- category = graphene.Node.get_node_from_global_id(- info, category, Category)- if not category:- return qs.none()- qs = qs.filter(category=category)+ if categories:+ categories = get_nodes(categories, Category)+ qs = filter_products_by_categories(qs, categories)++ if collections:+ collections = get_nodes(collections, Collection)+ qs = filter_products_by_collections(qs, collections)if stock_availability:qs = qs.annotate(total_quantity=Sum('variants__quantity'))@@ -78,6 +83,7 @@ def resolve_products(qs = filter_products_by_price(qs, price_lte, price_gte)qs = sort_qs(qs, sort_by)+ qs = qs.distinct()return gql_optimizer.query(qs, info)diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 1692767d68..2049108926 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -54,16 +54,19 @@ class ProductQueries(graphene.ObjectType):Product,attributes=graphene.List(AttributeScalar, description='Filter products by attributes.'),- category=graphene.ID(description='Filter products by category.'),+ categories=graphene.List(+ graphene.ID, description='Filter products by category.'),+ collections=graphene.List(+ graphene.ID, description='Filter products by collections.'),price_lte=graphene.Float(description='Filter by price less than or equal to the given value.'),price_gte=graphene.Float(description='Filter by price greater than or equal to the given value.'),sort_by=graphene.String(description='Sort products.'),- query=graphene.String(description=DESCRIPTIONS['product']),stock_availability=graphene.Argument(StockAvailability,description='Filter products by the stock availability'),+ query=graphene.String(description=DESCRIPTIONS['product']),description='List of the shop\'s products.')product_type = graphene.Field(ProductType, id=graphene.Argument(graphene.ID, required=True),@@ -100,12 +103,8 @@ class ProductQueries(graphene.ObjectType):def resolve_product(self, info, id):return graphene.Node.get_node_from_global_id(info, id, Product)- def resolve_products(- self, info, attributes=None, category=None, stock_availability=None,- query=None, price_lte=None, price_gte=None, sort_by=None, **kwargs):- return resolve_products(- info, attributes, category, stock_availability, query,- price_lte, price_gte, sort_by)+ def resolve_products(self, info, **kwargs):+ return resolve_products(info, **kwargs)def resolve_product_type(self, info, id):return graphene.Node.get_node_from_global_id(info, id, ProductType)diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.pyindex d95ccece7b..8ad36f2b17 100644--- a/saleor/graphql/product/types.py+++ b/saleor/graphql/product/types.py@@ -347,25 +347,11 @@ class ProductType(CountableDjangoObjectType):qs = self.products.visible_to_user(info.context.user)return gql_optimizer.query(qs, info)- def resolve_variant_attributes(self, info):- return self.variant_attributes.prefetch_related('values')-- def resolve_product_attributes(self, info):- return self.product_attributes.prefetch_related('values')-class Collection(CountableDjangoObjectType):products = gql_optimizer.field(PrefetchingConnectionField(- Product,- attributes=graphene.List(- AttributeScalar, description='Filter products by attributes.'),- price_lte=graphene.Float(- description='Filter by price less than or equal to the given value.'),- price_gte=graphene.Float(- description='Filter by price greater than or equal to the given value.'),- sort_by=graphene.String(description='Sort products.'),- description='List of collection products.'),+ Product, description='List of products in this collection.'),prefetch_related=prefetch_products)background_image = graphene.Field(Image)@@ -378,34 +364,17 @@ class Collection(CountableDjangoObjectType):def resolve_background_image(self, info, **kwargs):return self.background_image or None- def resolve_products(- self, info, attributes=None, price_lte=None, price_gte=None,- sort_by=None, **kwargs):-- # FIXME: Fix prefetching products- # if hasattr(self, 'prefetched_products'):- # return self.prefetched_products-+ def resolve_products(self, info, **kwargs):+ if hasattr(self, 'prefetched_products'):+ return self.prefetched_productsqs = self.products.visible_to_user(info.context.user)- qs = filter_products_by_price(qs, price_lte, price_gte)- if attributes:- qs = filter_products_by_attributes(qs, attributes)- qs = sort_qs(qs, sort_by)return gql_optimizer.query(qs, info)class Category(CountableDjangoObjectType):products = gql_optimizer.field(PrefetchingConnectionField(- Product,- attributes=graphene.List(- AttributeScalar, description='Filter products by attributes.'),- price_lte=graphene.Float(- description='Filter by price less than or equal to the given value.'),- price_gte=graphene.Float(- description='Filter by price greater than or equal to the given value.'),- sort_by=graphene.String(description='Sort products.'),- description='List of products in the category.'),+ Product, description='List of products in the category.'),prefetch_related=prefetch_products)url = graphene.String(description='The storefront\'s URL for the category.')@@ -441,19 +410,10 @@ class Category(CountableDjangoObjectType):def resolve_url(self, info):return self.get_absolute_url()- def resolve_products(- self, info, attributes=None, price_lte=None, price_gte=None,- sort_by=None, **kwargs):-- # FIXME: Fix prefetching products- # if hasattr(self, 'prefetched_products'):- # return self.prefetched_products-+ def resolve_products(self, info, **kwargs):+ if hasattr(self, 'prefetched_products'):+ return self.prefetched_productsqs = self.products.visible_to_user(info.context.user)- qs = filter_products_by_price(qs, price_lte, price_gte)- if attributes:- qs = filter_products_by_attributes(qs, attributes)- qs = sort_qs(qs, sort_by)return gql_optimizer.query(qs, info)diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.pyindex 9465a561c8..ecd8bd66b3 100644--- a/saleor/graphql/utils.py+++ b/saleor/graphql/utils.py@@ -30,12 +30,13 @@ def get_nodes(ids, graphene_type=None):pks = []types = []for graphql_id in ids:- _type, _id = from_global_id(graphql_id)- if graphene_type:- assert str(graphene_type) == _type, (- 'Must receive an {} id.').format(graphene_type._meta.name)- pks.append(_id)- types.append(_type)+ if graphql_id:+ _type, _id = from_global_id(graphql_id)+ if graphene_type:+ assert str(graphene_type) == _type, (+ 'Must receive an {} id.').format(graphene_type._meta.name)+ pks.append(_id)+ types.append(_type)# If `graphene_type` was not provided, check if all resolved types are# the same. This prevents from accidentally mismatching IDs of differentdiff --git a/tests/api/test_graphql.py b/tests/api/test_graphql.pyindex 1bc5249b64..5005a17ca1 100644--- a/tests/api/test_graphql.py+++ b/tests/api/test_graphql.py@@ -50,6 +50,10 @@ def test_real_query(user_api_client, product):...CategoryPageFragmentQuery__typename}+ products(first: $first, sortBy: $sortBy, categories:[$categoryId], attributes: $attributesFilter, priceGte: $minPrice, priceLte: $maxPrice) {+ ...ProductListFragmentQuery+ __typename+ }attributes(inCategory: $categoryId) {edges {node {@@ -85,10 +89,6 @@ def test_real_query(user_api_client, product):}}}- products(first: $first, sortBy: $sortBy, attributes: $attributesFilter, priceGte: $minPrice, priceLte: $maxPrice) {- ...ProductListFragmentQuery- __typename- }__typename}diff --git a/tests/api/test_product.py b/tests/api/test_product.pyindex ac01b7278e..5721146d41 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -194,7 +194,7 @@ def test_filter_product_by_category(user_api_client, product):category = product.categoryquery = """query getProducts($categoryId: ID) {- products(category: $categoryId) {+ products(categories: [$categoryId]) {edges {node {name@@ -229,29 +229,67 @@ def test_fetch_product_by_id(user_api_client, product):assert product_data['name'] == product.name-def test_filter_product_by_attributes(user_api_client, product):+def test_filter_products_by_attributes(user_api_client, product):product_attr = product.product_type.product_attributes.first()- category = product.categoryattr_value = product_attr.values.first()filter_by = '%s:%s' % (product_attr.slug, attr_value.slug)query = """query {- category(id: "%(category_id)s") {- products(attributes: ["%(filter_by)s"]) {- edges {- node {- name- }+ products(attributes: ["%(filter_by)s"]) {+ edges {+ node {+ name+ }+ }+ }+ }+ """ % {'filter_by': filter_by}+ response = user_api_client.post_graphql(query)+ content = get_graphql_content(response)+ product_data = content['data']['products']['edges'][0]['node']+ assert product_data['name'] == product.name+++def test_filter_products_by_categories(+ user_api_client, categories_tree, product):+ category = categories_tree.children.first()+ product.category = category+ product.save()+ query = """+ query {+ products(categories: ["%(category_id)s"]) {+ edges {+ node {+ name}}}}- """ % {- 'category_id': graphene.Node.to_global_id('Category', category.id),- 'filter_by': filter_by}+ """ % {'category_id': graphene.Node.to_global_id('Category', category.id)}response = user_api_client.post_graphql(query)content = get_graphql_content(response)- product_data = content['data']['category']['products']['edges'][0]['node']+ product_data = content['data']['products']['edges'][0]['node']+ assert product_data['name'] == product.name+++def test_filter_products_by_collections(+ user_api_client, collection, product):+ collection.products.add(product)+ query = """+ query {+ products(collections: ["%(collection_id)s"]) {+ edges {+ node {+ name+ }+ }+ }+ }+ """ % {'collection_id': graphene.Node.to_global_id(+ 'Collection', collection.id)}+ response = user_api_client.post_graphql(query)+ content = get_graphql_content(response)+ product_data = content['data']['products']['edges'][0]['node']assert product_data['name'] == product.namediff --git a/tests/conftest.py b/tests/conftest.pyindex 67d31a98b3..ba66319457 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -227,6 +227,12 @@ def category(db): # pylint: disable=W0613return Category.objects.create(name='Default', slug='default')+def categories_tree(db):+ parent = Category.objects.create(name='Parent', slug='parent')+ parent.children.create(name='Child', slug='child')+ return parent+@pytest.fixturedef non_default_category(db): # pylint: disable=W0613return Category.objects.create(name='Not default', slug='not-default')