Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use filters in GraphQL
Patryk Zawadzki5c50336ac1b7
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex b1e67b04d1..f8723286bb 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -1,34 +1,39 @@import graphene-from graphene import relayfrom graphene_django.debug import DjangoDebug+from graphene_django.filter import DjangoFilterConnectionFieldfrom .product.types import (- CategoryType, ProductAttributeType, resolve_attributes, resolve_category)+ Category, ProductAttribute, Product, resolve_attributes,+ resolve_category, resolve_product)+from .product.filters import ProductFilterSetclass Query(graphene.ObjectType):attributes = graphene.List(- ProductAttributeType,- category_pk=graphene.Argument(graphene.Int, required=False))+ ProductAttribute,+ in_category=graphene.Argument(graphene.ID))+ categories = DjangoFilterConnectionField(Category)category = graphene.Field(- CategoryType,- pk=graphene.Argument(graphene.Int, required=True))- node = relay.Node.Field()- root = graphene.Field(lambda: Query)- debug = graphene.Field(DjangoDebug, name='_debug')-- def resolve_category(self, info, **args):- pk = args.get('pk')- return resolve_category(pk, info)-- def resolve_attributes(self, info, **args):- category_pk = args.get('category_pk')- return resolve_attributes(category_pk)-- def resolve_root(self, info):- # Re-expose the root query object. Workaround for the issue in Relay:- # https://github.com/facebook/relay/issues/112- return Query()+ Category,+ id=graphene.Argument(graphene.ID))+ product = graphene.Field(+ Product,+ id=graphene.Argument(graphene.ID))+ products = DjangoFilterConnectionField(+ Product, filterset_class=ProductFilterSet)+ node = graphene.Node.Field()+ debug = graphene.Field(DjangoDebug, name='__debug')++ def resolve_category(self, info, id):+ return graphene.Node.get_node_from_global_id(+ info, id, only_type=Category)++ def resolve_product(self, info, id):+ return graphene.Node.get_node_from_global_id(+ info, id, only_type=Product)++ def resolve_attributes(self, info, in_category=None):+ return resolve_attributes(in_category)schema = graphene.Schema(Query)diff --git a/saleor/graphql/core/types.py b/saleor/graphql/core/types.pyindex a0e59145f3..f2bd54c7aa 100644--- a/saleor/graphql/core/types.py+++ b/saleor/graphql/core/types.py@@ -2,7 +2,7 @@ import graphenefrom django_prices.templatetags import prices_i18n-class PriceType(graphene.ObjectType):+class Price(graphene.ObjectType):currency = graphene.String()gross = graphene.Float()gross_localized = graphene.String()@@ -16,6 +16,6 @@ class PriceType(graphene.ObjectType):return prices_i18n.net(self)-class PriceRangeType(graphene.ObjectType):- max_price = graphene.Field(lambda: PriceType)- min_price = graphene.Field(lambda: PriceType)+class PriceRange(graphene.ObjectType):+ max_price = graphene.Field(Price)+ min_price = graphene.Field(Price)diff --git a/saleor/graphql/fields.py b/saleor/graphql/fields.pynew file mode 100644index 0000000000..5a05570773--- /dev/null+++ b/saleor/graphql/fields.py@@ -0,0 +1,12 @@+import graphene+from django import forms+from graphene_django.form_converter import convert_form_field+++class AttributeField(forms.Field):+ pass+++@convert_form_field.register(AttributeField)+def convert_form_field_to_list(field):+ return graphene.List(graphene.String)diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pynew file mode 100644index 0000000000..e0d3dba166--- /dev/null+++ b/saleor/graphql/product/filters.py@@ -0,0 +1,65 @@+import functools+import operator+from collections import OrderedDict, defaultdict++from django.db.models import Q+from django_filters.fields import Lookup+from graphene_django.filter.filterset import Filter, FilterSet++from ..fields import AttributeField+from ...product.models import (+ AttributeChoiceValue, Category, Product, ProductAttribute, ProductImage,+ ProductVariant)+++class ProduductAttributeFilter(Filter):+ field_class = AttributeField++ def filter(self, qs, value):+ if isinstance(value, Lookup):+ value = value.value++ if not value:+ return qs.distinct() if self.distinct else qs++ attributes = ProductAttribute.objects.prefetch_related('values')+ attributes_map = {+ attribute.slug: attribute.pk for attribute in attributes}+ values_map = {+ attr.slug: {value.slug: value.pk for value in attr.values.all()}+ for attr in attributes}+ queries = defaultdict(list)+ # Convert attribute:value pairs into a dictionary where+ # attributes are keys and values are grouped in lists+ for pair in value:+ attr_name, val_slug = pair.split(':', 1)+ if attr_name not in attributes_map:+ raise ValueError('Unknown attribute name: %r' % (attr_name,))+ attr_pk = attributes_map[attr_name]+ attr_val_pk = values_map[attr_name].get(val_slug, val_slug)+ queries[attr_pk].append(attr_val_pk)+ # Combine filters of the same attribute with OR operator+ # and then combine full query with AND operator.+ combine_and = [functools.reduce(operator.or_, [+ Q(**{'variants__attributes__%s' % key: v}) |+ Q(**{'attributes__%s' % key: v})+ for v in values]) for key, values in queries.items()]+ query = functools.reduce(operator.and_, combine_and)+ qs = self.get_method(qs)(query)+ return qs.distinct() if self.distinct else qs+++class ProductFilterSet(FilterSet):+ class Meta:+ model = Product+ fields = {+ 'category': ['exact'],+ 'price': ['exact', 'range', 'lte', 'gte'],+ 'attributes': ['exact']}++ @classmethod+ def filter_for_field(cls, f, field_name, lookup_expr='exact'):+ if field_name == 'attributes':+ return ProduductAttributeFilter(+ field_name=field_name, lookup_expr=lookup_expr)+ return super().filter_for_field(f, field_name, lookup_expr=lookup_expr)diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.pyindex 95acade48d..6681c5cc9f 100644--- a/saleor/graphql/product/types.py+++ b/saleor/graphql/product/types.py@@ -4,15 +4,16 @@ import operatorimport graphenefrom django.db.models import Qfrom graphene import relay-from graphene_django import DjangoConnectionField, DjangoObjectType+from graphene.relay.node import from_global_id+from graphene_django import DjangoObjectType+from graphene_django.filter import DjangoFilterConnectionField-from ...product.models import (- AttributeChoiceValue, Category, Product, ProductAttribute, ProductImage,- ProductVariant)+from ...product import modelsfrom ...product.templatetags.product_images import product_first_imagefrom ...product.utils import get_availability, products_visible_to_user-from ..core.types import PriceRangeType, PriceType-from ..utils import CategoryAncestorsCache, DjangoPkInterface+from ..core.types import Price, PriceRange+from ..utils import CategoryAncestorsCache+from .filters import ProductFilterSetfrom .scalars import AttributesFilterScalarCONTEXT_CACHE_NAME = '__cache__'@@ -26,33 +27,32 @@ def get_ancestors_from_cache(category, context):return category.get_ancestors()-class ProductAvailabilityType(graphene.ObjectType):+class ProductAvailability(graphene.ObjectType):available = graphene.Boolean()on_sale = graphene.Boolean()- discount = graphene.Field(lambda: PriceType)- discount_local_currency = graphene.Field(lambda: PriceType)- price_range = graphene.Field(lambda: PriceRangeType)- price_range_undiscounted = graphene.Field(lambda: PriceRangeType)- price_range_local_currency = graphene.Field(lambda: PriceRangeType)+ discount = graphene.Field(Price)+ discount_local_currency = graphene.Field(Price)+ price_range = graphene.Field(PriceRange)+ price_range_undiscounted = graphene.Field(PriceRange)+ price_range_local_currency = graphene.Field(PriceRange)-class ProductType(DjangoObjectType):+class Product(DjangoObjectType):url = graphene.String()thumbnail_url = graphene.String(size=graphene.Argument(graphene.String,description="The size of a thumbnail, for example 255x255"))- images = graphene.List(lambda: ProductImageType)- variants = graphene.List(lambda: ProductVariantType)- availability = graphene.Field(lambda: ProductAvailabilityType)- price = graphene.Field(lambda: PriceType)+ images = graphene.List(lambda: ProductImage)+ variants = graphene.List(lambda: ProductVariant)+ availability = graphene.Field(lambda: ProductAvailability)+ price = graphene.Field(lambda: Price)class Meta:- model = Product- interfaces = (relay.Node, DjangoPkInterface)+ model = models.Product+ interfaces = [relay.Node]- def resolve_thumbnail_url(self, info, **args):- size = args.get('size')+ def resolve_thumbnail_url(self, info, *, size=None):if not size:size = '255x255'return product_first_image(self, size)@@ -68,36 +68,24 @@ class ProductType(DjangoObjectType):def resolve_availability(self, info):context = info.context- a = get_availability(self, context.discounts, context.currency)- return ProductAvailabilityType(**a._asdict())---class CategoryType(DjangoObjectType):- products = DjangoConnectionField(- ProductType,- attributes=graphene.Argument(- graphene.List(AttributesFilterScalar),- description="""A list of attribute:value pairs to filter- the products by"""),- order_by=graphene.Argument(- graphene.String,- description="""A name of field to sort the products by. The negative- sign in front of name implies descending order."""),- price_lte=graphene.Argument(- graphene.Float, description="""Get the products with price lower- than or equal to the given value"""),- price_gte=graphene.Argument(- graphene.Float, description="""Get the products with price greater- than or equal to the given value"""))+ availability = get_availability(+ self, context.discounts, context.currency)+ return ProductAvailability(**availability._asdict())+++class Category(DjangoObjectType):+ products = DjangoFilterConnectionField(+ Product, filterset_class=ProductFilterSet)products_count = graphene.Int()url = graphene.String()- ancestors = graphene.List(lambda: CategoryType)- children = graphene.List(lambda: CategoryType)- siblings = graphene.List(lambda: CategoryType)+ ancestors = DjangoFilterConnectionField(lambda: Category)+ children = DjangoFilterConnectionField(lambda: Category)+ siblings = DjangoFilterConnectionField(lambda: Category)class Meta:- model = Category- interfaces = (relay.Node, DjangoPkInterface)+ model = models.Category+ filter_fields = ['id', 'name']+ interfaces = [relay.Node]def resolve_ancestors(self, info):return get_ancestors_from_cache(self, info.context)@@ -120,85 +108,29 @@ class CategoryType(DjangoObjectType):qs = products_visible_to_user(context.user)qs = qs.prefetch_related('images', 'category', 'variants__stock')qs = qs.filter(category=self)-- attributes_filter, order_by, price_lte, price_gte = map(- args.get, ['attributes', 'order_by', 'price_lte', 'price_gte'])-- if attributes_filter:- attributes = ProductAttribute.objects.prefetch_related('values')- attributes_map = {attribute.slug: attribute.pk- for attribute in attributes}- values_map = {attr.slug: {value.slug: value.pk- for value in attr.values.all()}- for attr in attributes}- queries = {}- # Convert attribute:value pairs into a dictionary where- # attributes are keys and values are grouped in lists- for attr_name, val_slug in attributes_filter:- try:- attr_pk = attributes_map[attr_name]- except KeyError:- attr_pk = None- else:- try:- attr_val_pk = values_map[attr_name][val_slug]- except KeyError:- attr_val_pk = None- else:- if attr_val_pk is not None and attr_pk not in queries:- queries[attr_pk] = [attr_val_pk]- else:- queries[attr_pk].append(attr_val_pk)- if queries:- # Combine filters of the same attribute with OR operator- # and then combine full query with AND operator.- combine_and = [functools.reduce(operator.or_, [- Q(**{'variants__attributes__%s' % key: v}) |- Q(**{'attributes__%s' % key: v})- for v in values]) for key, values in queries.items()]- query = functools.reduce(operator.and_, combine_and)- qs = qs.filter(query).distinct()-- if order_by:- qs = qs.order_by(order_by)-- def filter_by_price(queryset, value, operator):- return [- obj for obj in queryset- if operator(- get_availability(obj, context.discounts)- .price_range.min_price.gross, value)- ]-- if price_lte:- qs = filter_by_price(qs, price_lte, operator.le)-- if price_gte:- qs = filter_by_price(qs, price_gte, operator.ge)return qs-class ProductVariantType(DjangoObjectType):+class ProductVariant(DjangoObjectType):stock_quantity = graphene.Int()- price_override = graphene.Field(lambda: PriceType)+ price_override = graphene.Field(lambda: Price)class Meta:- model = ProductVariant- interfaces = (relay.Node, DjangoPkInterface)+ model = models.ProductVariant+ interfaces = [relay.Node]def resolve_stock_quantity(self, info):return self.get_stock_quantity()-class ProductImageType(DjangoObjectType):+class ProductImage(DjangoObjectType):url = graphene.String(size=graphene.String())class Meta:- model = ProductImage- interfaces = (relay.Node, DjangoPkInterface)+ model = models.ProductImage+ interfaces = [relay.Node]- def resolve_url(self, info, **args):- size = args.get('size')+ def resolve_url(self, info, *, size=None):if size:return self.image.crop[size].urlreturn self.image.url@@ -206,23 +138,23 @@ class ProductImageType(DjangoObjectType):class ProductAttributeValue(DjangoObjectType):class Meta:- model = AttributeChoiceValue- interfaces = (relay.Node, DjangoPkInterface)+ model = models.AttributeChoiceValue+ interfaces = [relay.Node]-class ProductAttributeType(DjangoObjectType):+class ProductAttribute(DjangoObjectType):values = graphene.List(lambda: ProductAttributeValue)class Meta:- model = ProductAttribute- interfaces = (relay.Node, DjangoPkInterface)+ model = models.ProductAttribute+ interfaces = [relay.Node]def resolve_values(self, info):return self.values.all()-def resolve_category(pk, info):- categories = Category.tree.filter(pk=pk).get_cached_trees()+def resolve_category(id, info):+ categories = models.Category.tree.filter(id=id).get_cached_trees()if categories:category = categories[0]cache = {CACHE_ANCESTORS: CategoryAncestorsCache(category)}@@ -231,15 +163,20 @@ def resolve_category(pk, info):return None+def resolve_product(id, info):+ products = products_visible_to_user(info.context.user).filter(id=id)+ return products.first()++def resolve_attributes(category_pk):- queryset = ProductAttribute.objects.prefetch_related('values')+ queryset = models.ProductAttribute.objects.prefetch_related('values')if category_pk:# Get attributes that are used with product types# within the given category.- tree = Category.objects.get(+ tree = models.Category.objects.get(pk=category_pk).get_descendants(include_self=True)product_types = set(- [obj[0] for obj in Product.objects.filter(+ [obj[0] for obj in models.Product.objects.filter(category__in=tree).values_list('product_type_id')])queryset = queryset.filter(Q(product_types__in=product_types) |diff --git a/tests/test_graphql.py b/tests/test_graphql.pyindex 23afc00ac9..4956693d10 100644--- a/tests/test_graphql.py+++ b/tests/test_graphql.py@@ -1,5 +1,6 @@import json+import grapheneimport pytestfrom saleor.product.models import Category, ProductAttribute@@ -9,14 +10,9 @@ def get_content(response):return json.loads(response.content.decode('utf8'))-def assert_success(content):- assert 'errors' not in content- assert 'data' in content--def assert_corresponding_fields(iterable_data, queryset, fields):assert len(iterable_data) == queryset.count()- for (data, obj) in zip(iterable_data, queryset):+ for data, obj in zip(iterable_data, queryset):for field in fields:assert str(data[field]) == str(getattr(obj, field))@@ -26,30 +22,50 @@ def test_category_query(client, product_in_stock):category = Category.objects.first()query = """query {- category(pk: %(category_pk)s) {- pk+ category(id: "%(category_pk)s") {+ idnameproductsCount- ancestors { name }- children { name }- siblings { name }+ ancestors {+ edges {+ node {+ name+ }+ }+ }+ children {+ edges {+ node {+ name+ }+ }+ }+ siblings {+ edges {+ node {+ name+ }+ }+ }}}- """ % {'category_pk': category.pk}+ """ % {'category_pk': graphene.Node.to_global_id('Category', category.pk)}response = client.post('/graphql/', {'query': query})content = get_content(response)- assert_success(content)+ assert 'errors' not in contentcategory_data = content['data']['category']assert category_data is not None- assert int(category_data['pk']) == category.pkassert category_data['name'] == category.nameassert category_data['productsCount'] == category.products.count()- assert_corresponding_fields(- category_data['ancestors'], category.get_ancestors(), ['name'])- assert_corresponding_fields(- category_data['children'], category.get_children(), ['name'])- assert_corresponding_fields(- category_data['siblings'], category.get_siblings(), ['name'])+ assert (+ len(category_data['ancestors']['edges']) ==+ category.get_ancestors().count())+ assert (+ len(category_data['children']['edges']) ==+ category.get_children().count())+ assert (+ len(category_data['siblings']['edges']) ==+ category.get_siblings().count())@pytest.mark.django_db()@@ -58,11 +74,11 @@ def test_product_query(client, product_in_stock):product = category.products.first()query = """query {- category(pk: %(category_pk)s) {+ category(id: "%(category_id)s") {products {edges {node {- pk+ idnameurlthumbnailUrl@@ -86,30 +102,83 @@ def test_product_query(client, product_in_stock):}}}- """ % {'category_pk': category.pk}+ """ % {'category_id': graphene.Node.to_global_id('Category', category.id)}response = client.post('/graphql/', {'query': query})content = get_content(response)- assert_success(content)+ assert 'errors' not in contentassert content['data']['category'] is not Noneproduct_edges_data = content['data']['category']['products']['edges']assert len(product_edges_data) == category.products.count()product_data = product_edges_data[0]['node']- assert int(product_data['pk']) == product.pkassert product_data['name'] == product.nameassert product_data['url'] == product.get_absolute_url()gross = product_data['availability']['priceRange']['minPrice']['gross']assert float(gross) == float(product.price.gross)[email protected]_db()+def test_filter_product_by_category(client, product_in_stock):+ category = product_in_stock.category+ query = """+ query getProducts($categoryId: ID) {+ products(category: $categoryId) {+ edges {+ node {+ name+ }+ }+ }+ }+ """+ response = client.post(+ '/graphql/',+ {+ 'query': query,+ 'variables': json.dumps(+ {+ 'categoryId': graphene.Node.to_global_id(+ 'Category', category.id)}),+ 'operationName': 'getProducts'})+ content = get_content(response)+ assert 'errors' not in content+ product_data = content['data']['products']['edges'][0]['node']+ assert product_data['name'] == product_in_stock.name++[email protected]_db()+def test_fetch_product_by_id(client, product_in_stock):+ query = """+ query ($productId: ID!) {+ node(id: $productId) {+ ... on Product {+ name+ }+ }+ }+ """+ response = client.post(+ '/graphql/',+ {+ 'query': query,+ 'variables': json.dumps(+ {+ 'productId': graphene.Node.to_global_id(+ 'Product', product_in_stock.id)})})+ content = get_content(response)+ assert 'errors' not in content+ product_data = content['data']['node']+ assert product_data['name'] == product_in_stock.name++@pytest.mark.django_db()def test_filter_product_by_attributes(client, product_in_stock):- category = Category.objects.first()product_attr = product_in_stock.product_type.product_attributes.first()+ category = product_in_stock.categoryattr_value = product_attr.values.first()- filter_by = "%s:%s" % (product_attr.name, attr_value.slug)+ filter_by = "%s:%s" % (product_attr.slug, attr_value.slug)query = """query {- category(pk: %(category_pk)s) {+ category(id: "%(category_id)s") {products(attributes: ["%(filter_by)s"]) {edges {node {@@ -119,10 +188,12 @@ def test_filter_product_by_attributes(client, product_in_stock):}}}- """ % {'category_pk': category.pk, 'filter_by': filter_by}+ """ % {+ 'category_id': graphene.Node.to_global_id('Category', category.id),+ 'filter_by': filter_by}response = client.post('/graphql/', {'query': query})content = get_content(response)- assert_success(content)+ assert 'errors' not in contentproduct_data = content['data']['category']['products']['edges'][0]['node']assert product_data['name'] == product_in_stock.name@@ -133,11 +204,11 @@ def test_attributes_query(client, product_in_stock):query = """query {attributes {- pk+ idnameslugvalues {- pk+ idnameslug}@@ -146,9 +217,9 @@ def test_attributes_query(client, product_in_stock):"""response = client.post('/graphql/', {'query': query})content = get_content(response)- assert_success(content)+ assert 'errors' not in contentattributes_data = content['data']['attributes']- assert_corresponding_fields(attributes_data, attributes, ['pk', 'name'])+ assert_corresponding_fields(attributes_data, attributes, ['name'])@pytest.mark.django_db()@@ -156,12 +227,12 @@ def test_attributes_in_category_query(client, product_in_stock):category = Category.objects.first()query = """query {- attributes(categoryPk: %(category_pk)s) {- pk+ attributes(inCategory: %(category_pk)s) {+ idnameslugvalues {- pk+ idnameslug}@@ -170,4 +241,4 @@ def test_attributes_in_category_query(client, product_in_stock):""" % {'category_pk': category.pk}response = client.post('/graphql/', {'query': query})content = get_content(response)- assert_success(content)+ assert 'errors' not in content