Skip to content

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

Adjust where filtering by empty values (#13754)

Iga Karbowiakf9880f3bae59
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20ec25b6b5..3bf9cf993b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,11 +13,13 @@ in 3.17. Use `PaymentSettings.defaultTransactionFlowStrategy` instead.
- Change in the CSV export. It will now use empty string for empty attribute values instead of a single whitespace value.
### GraphQL API
+- Adjust where filtering by empty values - explicit treat empty values - #13754 by @IKarbowiak
- Add `storedPaymentMethodRequestDelete` mutation - #13660 by @korycins
- Add `PaymentSettings` to `Channel` - #13677 by @korycins
- Add `externalReference` to `updateWarehouse`. It will allow update warehouse by
external reference. - #13342 by @Smit-Parmar
+
### Saleor Apps
- Add `STORED_PAYMENT_METHOD_DELETE_REQUESTED` webhook event - #13660 by @korycins
- Add `NOTIFY_CUSTOMER` flag to `FulfillmentCreated` type - #13620, by @Air-t
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.py
index 945ed82326..2d3de42087 100644
--- a/saleor/graphql/attribute/filters.py
+++ b/saleor/graphql/attribute/filters.py
@@ -12,12 +12,16 @@ from ..core.descriptions import ADDED_IN_311, PREVIEW_FEATURE
from ..core.doc_category import DOC_CATEGORY_ATTRIBUTES
from ..core.enums import MeasurementUnitsEnum
from ..core.filters import (
+ BooleanWhereFilter,
EnumFilter,
GlobalIDFilter,
GlobalIDMultipleChoiceFilter,
+ GlobalIDMultipleChoiceWhereFilter,
+ GlobalIDWhereFilter,
ListObjectTypeFilter,
MetadataFilterBase,
- OperationObjectTypeFilter,
+ MetadataWhereFilterBase,
+ OperationObjectTypeWhereFilter,
filter_slug_list,
)
from ..core.types import (
@@ -30,7 +34,7 @@ from ..core.types import (
from ..core.types.filter_input import FilterInputDescriptions, WhereInputObjectType
from ..core.utils import from_global_id_or_error
from ..utils import get_user_or_app_from_context
-from ..utils.filters import filter_by_id, filter_by_string_field
+from ..utils.filters import filter_by_ids, filter_where_by_string_field
from .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
@@ -193,11 +197,11 @@ class MeasurementUnitsEnumFilterInput(BaseInputObjectType):
def filter_attribute_name(qs, _, value):
- return filter_by_string_field(qs, "name", value)
+ return filter_where_by_string_field(qs, "name", value)
def filter_attribute_slug(qs, _, value):
- return filter_by_string_field(qs, "slug", value)
+ return filter_where_by_string_field(qs, "slug", value)
def filter_with_choices(qs, _, value):
@@ -206,68 +210,74 @@ def filter_with_choices(qs, _, value):
return qs.filter(lookup)
elif value is False:
return qs.exclude(lookup)
- return qs
+ return qs.none()
def filter_attribute_input_type(qs, _, value):
- return filter_by_string_field(qs, "input_type", value)
+ return filter_where_by_string_field(qs, "input_type", value)
def filter_attribute_entity_type(qs, _, value):
- return filter_by_string_field(qs, "entity_type", value)
+ return filter_where_by_string_field(qs, "entity_type", value)
def filter_attribute_type(qs, _, value):
- return filter_by_string_field(qs, "type", value)
+ return filter_where_by_string_field(qs, "type", value)
def filter_attribute_unit(qs, _, value):
- return filter_by_string_field(qs, "unit", value)
+ return filter_where_by_string_field(qs, "unit", value)
-class AttributeWhere(MetadataFilterBase):
- ids = GlobalIDMultipleChoiceFilter(method=filter_by_id("Attribute"))
- name = OperationObjectTypeFilter(
+def where_filter_attributes_by_product_types(qs, field, value, requestor, channel_slug):
+ if not value:
+ return qs.none()
+
+ return filter_attributes_by_product_types(qs, field, value, requestor, channel_slug)
+
+
+class AttributeWhere(MetadataWhereFilterBase):
+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Attribute"))
+ name = OperationObjectTypeWhereFilter(
input_class=StringFilterInput, method=filter_attribute_name
)
- slug = OperationObjectTypeFilter(
+ slug = OperationObjectTypeWhereFilter(
input_class=StringFilterInput, method=filter_attribute_slug
)
- with_choices = django_filters.BooleanFilter(method=filter_with_choices)
- input_type = OperationObjectTypeFilter(
+ with_choices = BooleanWhereFilter(method=filter_with_choices)
+ input_type = OperationObjectTypeWhereFilter(
AttributeInputTypeEnumFilterInput, method=filter_attribute_input_type
)
- entity_type = OperationObjectTypeFilter(
+ entity_type = OperationObjectTypeWhereFilter(
AttributeEntityTypeEnumFilterInput, method=filter_attribute_entity_type
)
- type = OperationObjectTypeFilter(
+ type = OperationObjectTypeWhereFilter(
AttributeTypeEnumFilterInput, method=filter_attribute_type
)
- unit = OperationObjectTypeFilter(
+ unit = OperationObjectTypeWhereFilter(
MeasurementUnitsEnumFilterInput, method=filter_attribute_unit
)
- in_collection = GlobalIDFilter(method="filter_in_collection")
- in_category = GlobalIDFilter(method="filter_in_category")
+ in_collection = GlobalIDWhereFilter(method="filter_in_collection")
+ in_category = GlobalIDWhereFilter(method="filter_in_category")
+ value_required = BooleanWhereFilter()
+ visible_in_storefront = BooleanWhereFilter()
+ filterable_in_dashboard = BooleanWhereFilter()
class Meta:
model = Attribute
- fields = [
- "value_required",
- "visible_in_storefront",
- "filterable_in_dashboard",
- ]
+ fields = []
def filter_in_collection(self, qs, name, value):
requestor = get_user_or_app_from_context(self.request)
channel_slug = get_channel_slug_from_filter_data(self.data)
- return filter_attributes_by_product_types(
+ return where_filter_attributes_by_product_types(
qs, name, value, requestor, channel_slug
)
def filter_in_category(self, qs, name, value):
requestor = get_user_or_app_from_context(self.request)
channel_slug = get_channel_slug_from_filter_data(self.data)
- return filter_attributes_by_product_types(
+ return where_filter_attributes_by_product_types(
qs, name, value, requestor, channel_slug
)
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_where.py b/saleor/graphql/attribute/tests/queries/test_attribute_where.py
index dec71bc2a8..5ae47f8523 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_where.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_where.py
@@ -49,6 +49,32 @@ def test_attributes_filter_by_ids(api_client, product_type_attribute_list):
}
+def test_attributes_filter_by_none_as_ids(api_client, product_type_attribute_list):
+ # given
+ variables = {"where": {"ids": None}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ attributes = data["data"]["attributes"]["edges"]
+ assert len(attributes) == 0
+
+
+def test_attributes_filter_by_ids_empty_list(api_client, product_type_attribute_list):
+ # given
+ variables = {"where": {"ids": []}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ attributes = data["data"]["attributes"]["edges"]
+ assert len(attributes) == 0
+
+
@pytest.mark.parametrize(
"where, indexes",
[
@@ -56,6 +82,11 @@ def test_attributes_filter_by_ids(api_client, product_type_attribute_list):
({"eq": "test"}, []),
({"oneOf": ["Color", "Text"]}, [0, 2]),
({"oneOf": ["a", "acd"]}, []),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": ""}, []),
+ ({"eq": None}, []),
+ (None, []),
],
)
def test_attributes_filter_by_name(
@@ -83,6 +114,11 @@ def test_attributes_filter_by_name(
({"eq": "test"}, []),
({"oneOf": ["color", "text"]}, [0, 2]),
({"oneOf": ["a", "acd"]}, []),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": ""}, []),
+ ({"eq": None}, []),
+ (None, []),
],
)
def test_attributes_filter_by_slug(
@@ -103,7 +139,7 @@ def test_attributes_filter_by_slug(
assert returned_attrs == {attributes[index].slug for index in indexes}
[email protected]("value, indexes", [(True, [0]), (False, [1, 2])])
[email protected]("value, indexes", [(True, [0]), (False, [1, 2]), (None, [])])
def test_attributes_filter_by_with_choices(
value, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
):
@@ -145,6 +181,10 @@ def test_attributes_filter_by_with_choices(
},
[],
),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": None}, []),
+ (None, []),
],
)
def test_attributes_filter_by_input_type(
@@ -187,6 +227,10 @@ def test_attributes_filter_by_input_type(
},
[],
),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": None}, [0]),
+ (None, []),
],
)
def test_attributes_filter_by_entity_type(
@@ -203,6 +247,9 @@ def test_attributes_filter_by_entity_type(
product_type_page_reference_attribute,
page_type_variant_reference_attribute,
]
+ color_attribute.entity_type = None
+ color_attribute.save(update_fields=["entity_type"])
+
variables = {"where": {"entityType": where}}
# when
@@ -238,6 +285,9 @@ def test_attributes_filter_by_entity_type(
},
[],
),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": None}, []),
],
)
def test_attributes_filter_by_type(
@@ -287,6 +337,9 @@ def test_attributes_filter_by_type(
},
[],
),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": None}, [0, 3]),
],
)
def test_attributes_filter_by_unit(
@@ -325,7 +378,7 @@ def test_attributes_filter_by_unit(
assert returned_attrs == {attributes[index].slug for index in indexes}
[email protected]("value, indexes", [(True, [0, 1]), (False, [2])])
[email protected]("value, indexes", [(True, [0, 1]), (False, [2]), (None, [])])
def test_attributes_filter_by_value_required(
value, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
):
@@ -351,7 +404,7 @@ def test_attributes_filter_by_value_required(
assert returned_attrs == {attributes[index].slug for index in indexes}
[email protected]("value, indexes", [(True, [0, 1]), (False, [2])])
[email protected]("value, indexes", [(True, [0, 1]), (False, [2]), (None, [])])
def test_attributes_filter_by_visible_in_storefront(
value,
indexes,
@@ -386,7 +439,7 @@ def test_attributes_filter_by_visible_in_storefront(
assert returned_attrs == {attributes[index].slug for index in indexes}
[email protected]("value, indexes", [(True, [0]), (False, [1, 2])])
[email protected]("value, indexes", [(True, [0]), (False, [1, 2]), (None, [])])
def test_attributes_filter_by_filterable_in_dashboard(
value, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
):
@@ -780,6 +833,54 @@ def test_attributes_filter_attributes_in_collection_object_with_given_id_does_no
assert content["data"]["attributes"]["edges"] == []
+def test_attributes_filter_in_collection_empty_value(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ collection,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ variables = {
+ "where": {
+ "inCollection": None,
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == 0
+
+
def test_attributes_filter_in_category_not_visible_in_listings_by_customer(
user_api_client, product_list, weight_attribute, channel_USD
):
@@ -1311,6 +1412,50 @@ def test_attributes_filter_in_category_object_with_given_id_does_not_exist(
assert content["data"]["attributes"]["edges"] == []
+def test_attributes_filter_in_category_empty_value(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ variables = {
+ "where": {
+ "inCategory": None,
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == 0
+
+
def test_attributes_filter_and_where_both_used(api_client, product_type_attribute_list):
# given
query = """
diff --git a/saleor/graphql/core/filters.py b/saleor/graphql/core/filters.py
index 00bc3cafc0..be5abf3839 100644
--- a/saleor/graphql/core/filters.py
+++ b/saleor/graphql/core/filters.py
@@ -1,8 +1,10 @@
import django_filters
import graphene
from django.core.exceptions import ValidationError
-from django.forms import CharField, Field, MultipleChoiceField
+from django.db import models
+from django.forms import CharField, Field, MultipleChoiceField, NullBooleanField
from django_filters import Filter, MultipleChoiceFilter
+from django_filters.filters import FilterMethod
from graphql_relay import from_global_id
from ..utils.filters import filter_range_field
@@ -176,3 +178,142 @@ class GlobalIDMultipleChoiceFilter(MultipleChoiceFilter):
def filter(self, qs, value):
gids = [from_global_id(v)[1] for v in value]
return super(GlobalIDMultipleChoiceFilter, self).filter(qs, gids)
+
+
+class WhereFilterSet(django_filters.FilterSet):
+ """Implementation of FilterSet for where filtering.
+
+ Should be used for all where FilterSet classes.
+ """
+
+ def filter_queryset(self, queryset):
+ """Filter the queryset.
+
+ Filter the queryset with the underlying form's `cleaned_data`. You must
+ call `is_valid()` or `errors` before calling this method.
+
+ This method should be overridden if additional filtering needs to be
+ applied to the queryset before it is cached.
+ """
+ for name, value in self.form.cleaned_data.items():
+ # Ensure that we not filter by fields that were not provided in the input.
+ # The cleaned_data has all filter fields, but we only want to filter
+ # by those that were specified in the query.
+ if name not in self.form.data:
+ continue
+ queryset = self.filters[name].filter(queryset, value)
+ assert isinstance(
+ queryset, models.QuerySet
+ ), "Expected '%s.%s' to return a QuerySet, but got a %s instead." % (
+ type(self).__name__,
+ name,
+ type(queryset).__name__,
+ )
+ return queryset
+
+
+class MetadataWhereFilterBase(WhereFilterSet):
+ metadata = ListObjectTypeFilter(input_class=MetadataFilter, method=filter_metadata)
+
+ class Meta:
+ abstract = True
+
+
+class WhereFilter(Filter):
+ def method(): # type: ignore
+ # Filter method needs to be lazily resolved, as it may be dependent on
+ # the 'parent' FilterSet.
+
+ def fget(self):
+ return self._method
+
+ def fset(self, value):
+ self._method = value
+
+ # clear existing FilterMethod
+ if isinstance(self.filter, WhereFilterMethod):
+ del self.filter
+
+ # override filter w/ FilterMethod.
+ if value is not None:
+ self.filter = WhereFilterMethod(self)
+
+ return locals()
+
+ method = property(**method()) # type: ignore
+
+ def filter(self, qs, value):
+ if self.distinct:
+ qs = qs.distinct()
+ lookup = "%s__%s" % (self.field_name, self.lookup_expr)
+ qs = self.get_method(qs)(**{lookup: value})
+ return qs
+
+
+class WhereFilterMethod(FilterMethod):
+ def __call__(self, qs, value):
+ """Override the default FilterMethod to allow filtering by empty values."""
+ return self.method(qs, self.f.field_name, value)
+
+
+class ObjectTypeWhereFilter(WhereFilter):
+ def __init__(self, input_class, *args, **kwargs):
+ self.input_class = input_class
+ super().__init__(*args, **kwargs)
+
+
+class OperationObjectTypeWhereFilter(WhereFilter):
+ field_class = DefaultOperationField
+
+ def __init__(self, input_class, *args, **kwargs):
+ self.input_class = input_class
+ super().__init__(*args, **kwargs)
+
+
+class ListObjectTypeWhereFilter(MultipleChoiceFilter, WhereFilter):
+ field_class = DefaultMultipleChoiceField
+
+ def __init__(self, input_class, *args, **kwargs):
+ self.input_class = input_class
+ super().__init__(*args, **kwargs)
+
+
+class BooleanWhereFilter(WhereFilter):
+ field_class = NullBooleanField
+
+
+class CharWhereFilter(WhereFilter):
+ field_class = CharField
+
+
+class EnumWhereFilter(CharWhereFilter):
+ """Wheer filter class for Graphene enum object.
+
+ enum_class needs to be passed explicitly as well as the method.
+ """
+
+ def __init__(self, input_class, *args, **kwargs):
+ assert kwargs.get(
+ "method"
+ ), "Providing exact filter method is required for EnumFilter"
+ self.input_class = input_class
+ super().__init__(*args, **kwargs)
+
+
+class GlobalIDMultipleChoiceWhereFilter(MultipleChoiceFilter, WhereFilter):
+ field_class = GlobalIDMultipleChoiceField
+
+ def filter(self, qs, value):
+ gids = [from_global_id(v)[1] for v in value]
+ return super(GlobalIDMultipleChoiceWhereFilter, self).filter(qs, gids)
+
+
+class GlobalIDWhereFilter(WhereFilter):
+ field_class = GlobalIDFormField
+
+ def filter(self, qs, value):
+ """Convert the filter value to a primary key before filtering."""
+ _id = None
+ if value is not None:
+ _, _id = from_global_id(value)
+ return super(GlobalIDFilter, self).filter(qs, _id) # type: ignore
diff --git a/saleor/graphql/core/types/converter.py b/saleor/graphql/core/types/converter.py
index 1c9251a334..2a2ae9b5cf 100644
--- a/saleor/graphql/core/types/converter.py
+++ b/saleor/graphql/core/types/converter.py
@@ -8,11 +8,15 @@ from django.core.exceptions import ImproperlyConfigured
from ..filters import (
EnumFilter,
+ EnumWhereFilter,
GlobalIDFormField,
GlobalIDMultipleChoiceField,
ListObjectTypeFilter,
+ ListObjectTypeWhereFilter,
ObjectTypeFilter,
+ ObjectTypeWhereFilter,
OperationObjectTypeFilter,
+ OperationObjectTypeWhereFilter,
)
from .common import NonNullList
@@ -52,8 +56,11 @@ def convert_form_field_to_float(field):
)
+@convert_form_field.register(OperationObjectTypeWhereFilter)
@convert_form_field.register(OperationObjectTypeFilter)
+@convert_form_field.register(ObjectTypeWhereFilter)
@convert_form_field.register(ObjectTypeFilter)
+@convert_form_field.register(EnumWhereFilter)
@convert_form_field.register(EnumFilter)
def convert_convert_enum(field):
return field.input_class(description=get_form_field_description(field))
@@ -64,6 +71,7 @@ def convert_form_field_to_id(field):
return graphene.ID(required=field.required)
+@convert_form_field.register(ListObjectTypeWhereFilter)
@convert_form_field.register(ListObjectTypeFilter)
def convert_list_object_type(field):
return NonNullList(field.input_class, description=get_form_field_description(field))
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index a23d466e2f..71578d4070 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -39,12 +39,18 @@ from ..channel.filters import get_channel_slug_from_filter_data
from ..core.descriptions import ADDED_IN_38
from ..core.doc_category import DOC_CATEGORY_PRODUCTS
from ..core.filters import (
+ BooleanWhereFilter,
EnumFilter,
+ EnumWhereFilter,
GlobalIDMultipleChoiceFilter,
+ GlobalIDMultipleChoiceWhereFilter,
ListObjectTypeFilter,
+ ListObjectTypeWhereFilter,
MetadataFilterBase,
+ MetadataWhereFilterBase,
ObjectTypeFilter,
- OperationObjectTypeFilter,
+ ObjectTypeWhereFilter,
+ OperationObjectTypeWhereFilter,
filter_slug_list,
)
from ..core.types import (
@@ -65,10 +71,12 @@ from ..core.types.filter_input import (
from ..utils import resolve_global_ids_to_primary_keys
from ..utils.filters import (
filter_by_id,
- filter_by_string_field,
+ filter_by_ids,
filter_range_field,
filter_where_by_id_field,
filter_where_by_numeric_field,
+ filter_where_by_string_field,
+ filter_where_range_field,
)
from ..warehouse import types as warehouse_types
from . import types as product_types
@@ -810,93 +818,263 @@ class ProductFilter(MetadataFilterBase):
return _filter_stock_availability(queryset, name, value, channel_slug)
-class ProductWhere(MetadataFilterBase):
- ids = GlobalIDMultipleChoiceFilter(method=filter_by_id("Product"))
- name = OperationObjectTypeFilter(
+def where_filter_products_is_available(qs, _, value, channel_slug):
+ if value is None:
+ return qs.none()
+ channel = Channel.objects.filter(slug=channel_slug).values("pk")
+ now = datetime.datetime.now(pytz.UTC)
+ if value:
+ product_channel_listings = ProductChannelListing.objects.filter(
+ Exists(channel.filter(pk=OuterRef("channel_id"))),
+ available_for_purchase_at__lte=now,
+ ).values("product_id")
+ else:
+ product_channel_listings = ProductChannelListing.objects.filter(
+ Exists(channel.filter(pk=OuterRef("channel_id"))),
+ Q(available_for_purchase_at__gt=now)
+ | Q(available_for_purchase_at__isnull=True),
+ ).values("product_id")
+
+ return qs.filter(Exists(product_channel_listings.filter(product_id=OuterRef("pk"))))
+
+
+def where_filter_products_channel_field_from_date(qs, _, value, channel_slug, field):
+ if value is None:
+ return qs.none()
+ channel = Channel.objects.filter(slug=channel_slug).values("pk")
+ lookup = {
+ f"{field}__lte": value,
+ }
+ product_channel_listings = ProductChannelListing.objects.filter(
+ Exists(channel.filter(pk=OuterRef("channel_id"))),
+ **lookup,
+ ).values("product_id")
+
+ return qs.filter(Exists(product_channel_listings.filter(product_id=OuterRef("pk"))))
+
+
+def where_filter_has_category(qs, _, value):
+ if value is None:
+ return qs.none()
+ return qs.filter(category__isnull=not value)
+
+
+def where_filter_attributes(qs, _, value):
+ if not value:
+ return qs.none()
+
+ value_list = []
+ boolean_list = []
+ value_range_list = []
+ date_range_list = []
+ date_time_range_list = []
+
+ for v in value:
+ slug = v["slug"]
+ if "values" in v:
+ value_list.append((slug, v["values"]))
+ elif "values_range" in v:
+ value_range_list.append((slug, v["values_range"]))
+ elif "date" in v:
+ date_range_list.append((slug, v["date"]))
+ elif "date_time" in v:
+ date_time_range_list.append((slug, v["date_time"]))
+ elif "boolean" in v:
+ boolean_list.append((slug, v["boolean"]))
+
+ qs = filter_products_by_attributes(
+ qs,
+ value_list,
+ value_range_list,
+ boolean_list,
+ date_range_list,
+ date_time_range_list,
+ )
+ return qs
+
+
+def where_filter_stocks(qs, _, value):
+ if not value:
+ return qs.none()
+ warehouse_ids = value.get("warehouse_ids")
+ quantity = value.get("quantity")
+ if warehouse_ids and not quantity:
+ return where_filter_warehouses(qs, _, warehouse_ids)
+ if quantity and not warehouse_ids:
+ return where_filter_quantity(qs, quantity)
+ if quantity and warehouse_ids:
+ return where_filter_quantity(qs, quantity, warehouse_ids)
+ return qs.none()
+
+
+def where_filter_warehouses(qs, _, value):
+ if not value:
+ return qs.none()
+ _, warehouse_pks = resolve_global_ids_to_primary_keys(
+ value, warehouse_types.Warehouse
+ )
+ warehouses = Warehouse.objects.filter(pk__in=warehouse_pks).values("pk")
+ variant_ids = Stock.objects.filter(
+ Exists(warehouses.filter(pk=OuterRef("warehouse")))
+ ).values("product_variant_id")
+ variants = ProductVariant.objects.filter(id__in=variant_ids).values("pk")
+ return qs.filter(Exists(variants.filter(product=OuterRef("pk"))))
+
+
+def where_filter_quantity(qs, quantity_value, warehouse_ids=None):
+ """Filter products queryset by product variants quantity.
+
+ Return product queryset which contains at least one variant with aggregated quantity
+ between given range. If warehouses is given, it aggregates quantity only
+ from stocks which are in given warehouses.
+ """
+ stocks = Stock.objects.all()
+ if warehouse_ids:
+ _, warehouse_pks = resolve_global_ids_to_primary_keys(
+ warehouse_ids, warehouse_types.Warehouse
+ )
+ stocks = stocks.filter(warehouse_id__in=warehouse_pks)
+ stocks = stocks.values("product_variant_id").filter(
+ product_variant_id=OuterRef("pk")
+ )
+
+ stocks = Subquery(stocks.values_list(Sum("quantity")))
+ variants = ProductVariant.objects.annotate(
+ total_quantity=ExpressionWrapper(stocks, output_field=IntegerField())
+ )
+ variants = list(
+ filter_where_range_field(
+ variants, "total_quantity", quantity_value
+ ).values_list("product_id", flat=True)
+ )
+ return qs.filter(pk__in=variants)
+
+
+def where_filter_stock_availability(qs, _, value, channel_slug):
+ if value:
+ return filter_products_by_stock_availability(qs, value, channel_slug)
+ return qs.none()
+
+
+def where_filter_gift_card(qs, _, value):
+ if value is None:
+ return qs.none()
+
+ product_types = ProductType.objects.filter(kind=ProductTypeKind.GIFT_CARD)
+ lookup = Exists(product_types.filter(id=OuterRef("product_type_id")))
+ return qs.filter(lookup) if value is True else qs.exclude(lookup)
+
+
+def where_filter_has_preordered_variants(qs, _, value):
+ if value is None:
+ return qs.none()
+
+ variants = (
+ ProductVariant.objects.filter(is_preorder=True)
+ .filter(
+ Q(preorder_end_date__isnull=True) | Q(preorder_end_date__gt=timezone.now())
+ )
+ .values("product_id")
+ )
+ if value:
+ return qs.filter(Exists(variants.filter(product_id=OuterRef("pk"))))
+ else:
+ return qs.filter(~Exists(variants.filter(product_id=OuterRef("pk"))))
+
+
+def where_filter_updated_at_range(qs, _, value):
+ if value is None:
+ return qs.none()
+ return filter_where_range_field(qs, "updated_at", value)
+
+
+class ProductWhere(MetadataWhereFilterBase):
+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Product"))
+ name = OperationObjectTypeWhereFilter(
input_class=StringFilterInput,
method="filter_product_name",
help_text="Filter by product name.",
)
- slug = OperationObjectTypeFilter(
+ slug = OperationObjectTypeWhereFilter(
input_class=StringFilterInput,
method="filter_product_slug",
help_text="Filter by product slug.",
)
- product_type = OperationObjectTypeFilter(
+ product_type = OperationObjectTypeWhereFilter(
input_class=GlobalIDFilterInput,
method="filter_product_type",
help_text="Filter by product type.",
)
- category = OperationObjectTypeFilter(
+ category = OperationObjectTypeWhereFilter(
input_class=GlobalIDFilterInput,
method="filter_category",
help_text="Filter by product category.",
)
- collection = OperationObjectTypeFilter(
+ collection = OperationObjectTypeWhereFilter(
input_class=GlobalIDFilterInput,
method="filter_collection",
help_text="Filter by collection.",
)
- is_available = django_filters.BooleanFilter(
+ is_available = BooleanWhereFilter(
method="filter_is_available", help_text="Filter by availability for purchase."
)
- is_published = django_filters.BooleanFilter(
+ is_published = BooleanWhereFilter(
method="filter_is_published", help_text="Filter by public visibility."
)
- is_visible_in_listing = django_filters.BooleanFilter(
+ is_visible_in_listing = BooleanWhereFilter(
method="filter_is_listed", help_text="Filter by visibility on the channel."
)
- published_from = ObjectTypeFilter(
+ published_from = ObjectTypeWhereFilter(
input_class=graphene.DateTime,
method="filter_published_from",
help_text="Filter by the publication date.",
)
- available_from = ObjectTypeFilter(
+ available_from = ObjectTypeWhereFilter(
input_class=graphene.DateTime,
method="filter_available_from",
help_text="Filter by the date of availability for purchase.",
)
- has_category = django_filters.BooleanFilter(
- method=filter_has_category,
+ has_category = BooleanWhereFilter(
+ method=where_filter_has_category,
help_text="Filter by product with category assigned.",
)
- price = OperationObjectTypeFilter(
+ price = OperationObjectTypeWhereFilter(
input_class=DecimalFilterInput,
method="filter_variant_price",
help_text="Filter by product variant price.",
)
- minimal_price = OperationObjectTypeFilter(
+ minimal_price = OperationObjectTypeWhereFilter(
input_class=DecimalFilterInput,
method="filter_minimal_price",
field_name="minimal_price_amount",
help_text="Filter by the lowest variant price after discounts.",
)
- attributes = ListObjectTypeFilter(
+ attributes = ListObjectTypeWhereFilter(
input_class="saleor.graphql.attribute.types.AttributeInput",
method="filter_attributes",
help_text="Filter by attributes associated with the product.",
)
- stock_availability = EnumFilter(
+ stock_availability = EnumWhereFilter(
input_class=StockAvailability,
method="filter_stock_availability",
help_text="Filter by variants having specific stock status.",
)
- stocks = ObjectTypeFilter(
+ stocks = ObjectTypeWhereFilter(
input_class=ProductStockFilterInput,
- method=filter_stocks,
+ method=where_filter_stocks,
help_text="Filter by stock of the product variant.",
)
- gift_card = django_filters.BooleanFilter(
- method=filter_gift_card,
+ gift_card = BooleanWhereFilter(
+ method=where_filter_gift_card,
help_text="Filter on whether product is a gift card or not.",
)
- has_preordered_variants = django_filters.BooleanFilter(
- method=filter_has_preordered_variants,
+ has_preordered_variants = BooleanWhereFilter(
+ method=where_filter_has_preordered_variants,
help_text="Filter by product with preordered variants.",
)
- updated_at = ObjectTypeFilter(
+ updated_at = ObjectTypeWhereFilter(
input_class=DateTimeRangeInput,
- method=filter_updated_at_range,
+ method=where_filter_updated_at_range,
help_text="Filter by when was the most recent update.",
)
@@ -906,11 +1084,11 @@ class ProductWhere(MetadataFilterBase):
@staticmethod
def filter_product_name(qs, _, value):
- return filter_by_string_field(qs, "name", value)
+ return filter_where_by_string_field(qs, "name", value)
@staticmethod
def filter_product_slug(qs, _, value):
- return filter_by_string_field(qs, "slug", value)
+ return filter_where_by_string_field(qs, "slug", value)
@staticmethod
def filter_product_type(qs, _, value):
@@ -931,7 +1109,7 @@ class ProductWhere(MetadataFilterBase):
def filter_is_available(self, queryset, name, value):
channel_slug = get_channel_slug_from_filter_data(self.data)
- return _filter_products_is_available(
+ return where_filter_products_is_available(
queryset,
name,
value,
@@ -958,7 +1136,7 @@ class ProductWhere(MetadataFilterBase):
def filter_published_from(self, queryset, name, value):
channel_slug = get_channel_slug_from_filter_data(self.data)
- return _filter_products_channel_field_from_date(
+ return where_filter_products_channel_field_from_date(
queryset,
name,
value,
@@ -968,7 +1146,7 @@ class ProductWhere(MetadataFilterBase):
def filter_available_from(self, queryset, name, value):
channel_slug = get_channel_slug_from_filter_data(self.data)
- return _filter_products_channel_field_from_date(
+ return where_filter_products_channel_field_from_date(
queryset,
name,
value,
@@ -976,10 +1154,6 @@ class ProductWhere(MetadataFilterBase):
"available_for_purchase_at",
)
- @staticmethod
- def filter_has_category(qs, _, value):
- return qs.filter(category__isnull=not value)
-
def filter_variant_price(self, qs, _, value):
channel_slug = get_channel_slug_from_filter_data(self.data)
channel_id = Channel.objects.filter(slug=channel_slug).values("pk")
@@ -1009,11 +1183,11 @@ class ProductWhere(MetadataFilterBase):
@staticmethod
def filter_attributes(queryset, name, value):
- return _filter_attributes(queryset, name, value)
+ return where_filter_attributes(queryset, name, value)
def filter_stock_availability(self, queryset, name, value):
channel_slug = get_channel_slug_from_filter_data(self.data)
- return _filter_stock_availability(queryset, name, value, channel_slug)
+ return where_filter_stock_availability(queryset, name, value, channel_slug)
class ProductVariantFilter(MetadataFilterBase):
@@ -1037,8 +1211,8 @@ class ProductVariantFilter(MetadataFilterBase):
return queryset.filter(qs)
-class ProductVariantWhere(MetadataFilterBase):
- ids = GlobalIDMultipleChoiceFilter(method=filter_by_id("ProductVariant"))
+class ProductVariantWhere(MetadataWhereFilterBase):
+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("ProductVariant"))
class Meta:
model = ProductVariant
@@ -1072,8 +1246,8 @@ class CollectionFilter(MetadataFilterBase):
return queryset
-class CollectionWhere(MetadataFilterBase):
- ids = GlobalIDMultipleChoiceFilter(method=filter_by_id("Collection"))
+class CollectionWhere(MetadataWhereFilterBase):
+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Collection"))
class Meta:
model = Collection
@@ -1102,8 +1276,8 @@ class CategoryFilter(MetadataFilterBase):
return queryset.filter(name_slug_desc_qs)
-class CategoryWhere(MetadataFilterBase):
- ids = GlobalIDMultipleChoiceFilter(method=filter_by_id("Category"))
+class CategoryWhere(MetadataWhereFilterBase):
+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Category"))
class Meta:
model = Category
diff --git a/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.py b/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.py
index 6b896444ae..6d65472eab 100644
--- a/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.py
+++ b/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.py
@@ -37,3 +37,33 @@ def test_product_variant_filter_by_ids(api_client, product_variant_list, channel
product_variant_list[0].sku,
product_variant_list[1].sku,
}
+
+
+def test_product_variant_filter_by_none_as_ids(
+ api_client, product_variant_list, channel_USD
+):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"AND": [{"ids": None}]}}
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ variants = data["data"]["productVariants"]["edges"]
+ assert len(variants) == 0
+
+
+def test_product_variant_filter_by_ids_empty_list(
+ api_client, product_variant_list, channel_USD
+):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"AND": [{"ids": []}]}}
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ variants = data["data"]["productVariants"]["edges"]
+ assert len(variants) == 0
diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_where.py b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
index 2ed24e79e5..1a3f025148 100644
--- a/saleor/graphql/product/tests/queries/test_products_query_with_where.py
+++ b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
@@ -48,14 +48,43 @@ def test_product_filter_by_ids(api_client, product_list, channel_USD):
}
+def test_product_filter_by_none_as_ids(api_client, product_list, channel_USD):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"ids": None}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
+def test_product_filter_by_ids_empty_list(api_client, product_list, channel_USD):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"ids": []}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
@pytest.mark.parametrize(
"where, indexes",
[
({"eq": "Test product 1"}, [0]),
({"eq": "Non-existing"}, []),
+ ({"eq": None}, []),
+ ({"eq": ""}, []),
({"oneOf": ["Test product 1", "Test product 2"]}, [0, 1]),
({"oneOf": ["Test product 1", "Non-existing"]}, [0]),
({"oneOf": ["Non-existing 1", "Non-existing 2"]}, []),
+ (None, []),
],
)
def test_product_filter_by_name(where, indexes, api_client, product_list, channel_USD):
@@ -78,9 +107,12 @@ def test_product_filter_by_name(where, indexes, api_client, product_list, channe
[
({"eq": "test-product-a"}, [0]),
({"eq": "non-existing"}, []),
+ ({"eq": None}, []),
+ ({"eq": ""}, []),
({"oneOf": ["test-product-a", "test-product-b"]}, [0, 1]),
({"oneOf": ["test-product-a", "non-existing"]}, [0]),
({"oneOf": ["non-existing-1", "non-existing-2"]}, []),
+ (None, []),
],
)
def test_product_filter_by_slug(where, indexes, api_client, product_list, channel_USD):
@@ -154,6 +186,27 @@ def test_product_filter_by_product_type(
assert product_list[0].slug == products[0]["node"]["slug"]
+def test_product_filter_by_none_as_product_type(
+ api_client, product_list, channel_USD, product_type_list
+):
+ # given
+ product_list[0].product_type = product_type_list[0]
+ Product.objects.bulk_update(product_list, ["product_type"])
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"productType": {"eq": None}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
def test_product_filter_by_categories(
api_client, product_list, channel_USD, category_list
):
@@ -210,6 +263,27 @@ def test_product_filter_by_category(
assert product_list[1].slug == products[0]["node"]["slug"]
+def test_product_filter_by_none_as_category(
+ api_client, product_list, channel_USD, category_list
+):
+ # given
+ product_list[1].category = category_list[1]
+ Product.objects.bulk_update(product_list, ["category"])
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"category": {"eq": None}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
def test_product_filter_by_collections(
api_client, product_list, channel_USD, collection_list
):
@@ -260,9 +334,35 @@ def test_product_filter_by_collection(
assert product_list[1].slug == products[0]["node"]["slug"]
+def test_product_filter_by_none_as_collection(
+ api_client, product_list, channel_USD, collection_list
+):
+ # given
+ collection_list[1].products.add(product_list[1])
+ collection_id = graphene.Node.to_global_id("Collection", collection_list[1].pk)
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"collection": {"eq": collection_id}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert product_list[1].slug == products[0]["node"]["slug"]
+
+
@pytest.mark.parametrize(
"where, indexes",
- [({"isAvailable": True}, [0, 2]), ({"isAvailable": False}, [1])],
+ [
+ ({"isAvailable": True}, [0, 2]),
+ ({"isAvailable": False}, [1]),
+ ({"isAvailable": None}, []),
+ ],
)
def test_product_filter_by_is_available(
where, indexes, api_client, product_list, channel_USD
@@ -289,7 +389,11 @@ def test_product_filter_by_is_available(
@pytest.mark.parametrize(
"where, indexes",
- [({"isPublished": True}, [0, 2]), ({"isPublished": False}, [])],
+ [
+ ({"isPublished": True}, [0, 2]),
+ ({"isPublished": False}, []),
+ ({"isPublished": None}, []),
+ ],
)
def test_product_filter_by_is_published(
where, indexes, api_client, product_list, channel_USD
@@ -316,7 +420,11 @@ def test_product_filter_by_is_published(
@pytest.mark.parametrize(
"where, indexes",
- [({"isVisibleInListing": True}, [0, 2]), ({"isVisibleInListing": False}, [])],
+ [
+ ({"isVisibleInListing": True}, [0, 2]),
+ ({"isVisibleInListing": False}, []),
+ ({"isVisibleInListing": None}, []),
+ ],
)
def test_product_filter_by_is_visible_in_listing(
where, indexes, api_client, product_list, channel_USD
@@ -343,7 +451,11 @@ def test_product_filter_by_is_visible_in_listing(
@pytest.mark.parametrize(
"where, indexes",
- [({"hasCategory": True}, [0, 2]), ({"hasCategory": False}, [1])],
+ [
+ ({"hasCategory": True}, [0, 2]),
+ ({"hasCategory": False}, [1]),
+ ({"hasCategory": None}, []),
+ ],
)
def test_product_filter_by_has_category(
where, indexes, api_client, product_list, channel_USD
@@ -391,6 +503,31 @@ def test_product_filter_by_published_from(api_client, product_list, channel_USD)
assert product_list[0].slug == products[0]["node"]["slug"]
+def test_product_filter_by_none_as_published_from(
+ api_client, product_list, channel_USD
+):
+ # given
+ timestamp = timezone.now()
+ ProductChannelListing.objects.filter(
+ product__in=product_list, channel=channel_USD
+ ).update(published_at=timestamp + timedelta(days=1))
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).update(published_at=timestamp - timedelta(days=1))
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"publishedFrom": None},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
def test_product_filter_by_available_from(api_client, product_list, channel_USD):
# given
timestamp = timezone.now()
@@ -416,6 +553,31 @@ def test_product_filter_by_available_from(api_client, product_list, channel_USD)
assert product_list[2].slug == products[1]["node"]["slug"]
+def test_product_filter_by_none_as_available_from(
+ api_client, product_list, channel_USD
+):
+ # given
+ timestamp = timezone.now()
+ ProductChannelListing.objects.filter(
+ product__in=product_list, channel=channel_USD
+ ).update(available_for_purchase_at=timestamp - timedelta(days=1))
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).update(available_for_purchase_at=timestamp + timedelta(days=1))
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"availableFrom": None},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
@pytest.mark.parametrize(
"where, indexes",
[
@@ -426,6 +588,8 @@ def test_product_filter_by_available_from(api_client, product_list, channel_USD)
({"price": {"range": {"gte": 9.9999, "lte": 19.9999}}}, [0]),
({"price": {"eq": 20}}, [1]),
({"price": {"oneOf": [20, 30, 50]}}, [1, 2]),
+ ({"price": {"range": {"gte": None, "lte": None}}}, []),
+ ({"price": {"eq": None}}, []),
],
)
def test_product_filter_by_variant_price(
@@ -458,6 +622,8 @@ def test_product_filter_by_variant_price(
({"minimalPrice": {"range": {"gte": 9.9999, "lte": 19.9999}}}, [0]),
({"minimalPrice": {"eq": 20}}, [1]),
({"minimalPrice": {"oneOf": [20, 30, 50]}}, [1, 2]),
+ ({"minimalPrice": {"range": {"gte": None, "lte": None}}}, []),
+ ({"minimalPrice": {"eq": None}}, []),
],
)
def test_product_filter_by_minimal_price(
@@ -523,6 +689,46 @@ def test_products_filter_by_attributes(
assert products[0]["node"]["name"] == product.name
+def test_products_filter_by_attributes_empty_list(
+ api_client,
+ product_list,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ has_variants=True,
+ is_shipping_required=True,
+ kind=ProductTypeKind.NORMAL,
+ )
+ attribute = Attribute.objects.create(slug="new_attr", name="Attr")
+ attribute.product_types.add(product_type)
+ attr_value = AttributeValue.objects.create(
+ attribute=attribute, name="First", slug="first"
+ )
+ product = product_list[0]
+ product.product_type = product_type
+ product.save()
+ associate_attribute_values_to_instance(product, attribute, attr_value)
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 0
+
+
@pytest.mark.parametrize(
"values_range, indexes",
[
@@ -1083,6 +1289,7 @@ def test_products_filter_by_non_existing_attribute(
[
({"stockAvailability": "OUT_OF_STOCK"}, [0, 1, 2]),
({"stockAvailability": "IN_STOCK"}, [3]),
+ ({"stockAvailability": None}, []),
],
)
def test_products_filter_by_stock_availability(
@@ -1278,6 +1485,7 @@ def test_products_filter_by_stock_availability_only_stock_in_cc_warehouse(
({"lte": "210", "gte": "70"}, [], 1, [0]),
({"lte": "90"}, [], 1, [1]),
({"lte": "90", "gte": "75"}, [], 0, []),
+ ({"lte": None, "gte": None}, [], 0, []),
],
)
def test_products_filter_by_stocks(
@@ -1359,6 +1567,53 @@ def test_products_filter_by_stocks(
assert {node["node"]["id"] for node in products_data} == product_ids
+def test_products_filter_by_none_as_stocks(
+ api_client,
+ product_with_single_variant,
+ warehouse,
+ channel_USD,
+):
+ # given
+ variables = {
+ "where": {"stocks": None},
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products_data = content["data"]["products"]["edges"]
+ assert len(products_data) == 0
+
+
[email protected]("warehouse_ids", [[], None])
+def test_products_filter_by_empty_warehouse_ids(
+ warehouse_ids,
+ api_client,
+ product_with_single_variant,
+ warehouse,
+ channel_USD,
+):
+ # given
+ variables = {
+ "where": {
+ "stocks": {"quantity": {"gte": "110"}, "warehouseIds": warehouse_ids}
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products_data = content["data"]["products"]["edges"]
+
+ assert len(products_data) == 0
+
+
@pytest.mark.parametrize("filter,index", [(False, 0), (True, 1)])
def test_products_filter_by_gift_card(
filter,
@@ -1385,6 +1640,25 @@ def test_products_filter_by_gift_card(
)
+def test_products_filter_by_none_as_gift_card(
+ api_client,
+ product,
+ shippable_gift_card_product,
+ channel_USD,
+):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"giftCard": None}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 0
+
+
@pytest.mark.parametrize("filter,index", [(False, 0), (True, 1)])
def test_products_query_with_filter_has_preordered_variants(
filter,
@@ -1413,6 +1687,27 @@ def test_products_query_with_filter_has_preordered_variants(
assert products[0]["node"]["id"] == product_id
+def test_products_query_with_filter_none_as_has_preordered_variants(
+ api_client,
+ preorder_variant_global_threshold,
+ product_without_shipping,
+ channel_USD,
+):
+ # given
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"hasPreorderedVariants": None},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
def test_products_filter_by_has_preordered_variants_before_end_date(
api_client, preorder_variant_global_threshold, channel_USD
):
@@ -1481,6 +1776,27 @@ def test_product_filter_by_updated_at(api_client, product_list, channel_USD):
assert product_list[0].slug == products[0]["node"]["slug"]
+ "value", [{"gte": None}, {"lte": None}, {"gte": None, "lte": None}, None]
+)
+def test_product_filter_by_updated_at_empty_values(
+ value, api_client, product_list, channel_USD
+):
+ # given
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"updatedAt": value},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
def test_product_filter_with_operators(
api_client, product_list, channel_USD, product_type_list
):
diff --git a/saleor/graphql/product/tests/test_category_filtering.py b/saleor/graphql/product/tests/test_category_filtering.py
index d0659416d6..3a0e88cccd 100644
--- a/saleor/graphql/product/tests/test_category_filtering.py
+++ b/saleor/graphql/product/tests/test_category_filtering.py
@@ -632,3 +632,29 @@ def test_categories_where_by_ids(api_client, category_list):
category_list[0].slug,
category_list[1].slug,
}
+
+
+def test_categories_where_by_none_as_ids(api_client, category_list):
+ # given
+ variables = {"where": {"ids": None}}
+
+ # when
+ response = api_client.post_graphql(CATEGORY_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ categories = data["data"]["categories"]["edges"]
+ assert len(categories) == 0
+
+
+def test_categories_where_by_ids_empty_list(api_client, category_list):
+ # given
+ variables = {"where": {"AND": [{"ids": []}]}}
+
+ # when
+ response = api_client.post_graphql(CATEGORY_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ categories = data["data"]["categories"]["edges"]
+ assert len(categories) == 0
diff --git a/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
index b8c24a60b3..9f3f836b6e 100644
--- a/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
+++ b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
@@ -423,3 +423,29 @@ def test_collections_where_by_ids(api_client, collection_list, channel_USD):
collection_list[0].slug,
collection_list[1].slug,
}
+
+
+def test_collections_where_by_none_as_ids(api_client, collection_list, channel_USD):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"AND": [{"ids": None}]}}
+
+ # when
+ response = api_client.post_graphql(COLLECTION_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ collections = data["data"]["collections"]["edges"]
+ assert len(collections) == 0
+
+
+def test_collections_where_by_ids_empty_list(api_client, collection_list, channel_USD):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"ids": []}}
+
+ # when
+ response = api_client.post_graphql(COLLECTION_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ collections = data["data"]["collections"]["edges"]
+ assert len(collections) == 0
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 4e1bfceb5f..7d5fe2649b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -6494,9 +6494,6 @@ Added in Saleor 3.11.
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
input AttributeWhereInput @doc(category: "Attributes") {
- valueRequired: Boolean
- visibleInStorefront: Boolean
- filterableInDashboard: Boolean
metadata: [MetadataFilter!]
ids: [ID!]
name: StringFilterInput
@@ -6508,6 +6505,9 @@ input AttributeWhereInput @doc(category: "Attributes") {
unit: MeasurementUnitsEnumFilterInput
inCollection: ID
inCategory: ID
+ valueRequired: Boolean
+ visibleInStorefront: Boolean
+ filterableInDashboard: Boolean
"""List of conditions that must be met."""
AND: [AttributeWhereInput!]
diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.py
index c54d3a2985..1ba045e3de 100644
--- a/saleor/graphql/utils/filters.py
+++ b/saleor/graphql/utils/filters.py
@@ -39,6 +39,10 @@ def filter_range_field(qs, field, value):
def filter_by_id(object_type):
+ """Use only in standard filters.
+
+ Returns entering qs when value is empty.
+ """
from . import resolve_global_ids_to_primary_keys
def inner(qs, _, value):
@@ -50,16 +54,44 @@ def filter_by_id(object_type):
return inner
-def filter_by_string_field(
+def filter_by_ids(object_type):
+ """Use in where filters.
+
+ Returns empty qs when value is empty.
+ """
+ from . import resolve_global_ids_to_primary_keys
+
+ def inner(qs, _, value):
+ _, obj_pks = resolve_global_ids_to_primary_keys(value, object_type)
+ return qs.filter(id__in=obj_pks)
+
+ return inner
+
+
+def filter_where_range_field(qs, field, value):
+ gte, lte = value.get("gte"), value.get("lte")
+ if gte is None and lte is None:
+ return qs.none()
+ if gte is not None:
+ lookup = {f"{field}__gte": gte}
+ qs = qs.filter(**lookup)
+ if lte is not None:
+ lookup = {f"{field}__lte": lte}
+ qs = qs.filter(**lookup)
+ return qs
+
+
+def filter_where_by_string_field(
qs: "QuerySet", field: str, value: Dict[str, Union[str, List[str]]]
):
- eq = value.get("eq")
- one_of = value.get("one_of")
- if eq:
- qs = qs.filter(**{field: eq})
- if one_of:
- qs = qs.filter(**{f"{field}__in": one_of})
- return qs
+ if value is None:
+ return qs.none()
+ if "eq" in value:
+ # allow filtering by `None` value
+ return qs.filter(**{field: value["eq"]})
+ if one_of := value.get("one_of"):
+ return qs.filter(**{f"{field}__in": one_of})
+ return qs.none()
def filter_where_by_id_field(
@@ -71,11 +103,11 @@ def filter_where_by_id_field(
one_of = value.get("one_of")
if eq and isinstance(eq, str):
_, pks = resolve_global_ids_to_primary_keys([eq], type, True)
- qs = qs.filter(**{field: pks[0]})
+ return qs.filter(**{field: pks[0]})
if one_of:
_, pks = resolve_global_ids_to_primary_keys(one_of, type, True)
- qs = qs.filter(**{f"{field}__in": pks})
- return qs
+ return qs.filter(**{f"{field}__in": pks})
+ return qs.none()
def filter_where_by_numeric_field(
@@ -83,19 +115,22 @@ def filter_where_by_numeric_field(
field: str,
value: Dict[str, Union[Number, List[Number], Dict[str, Number]]],
):
- eq = value.get("eq")
one_of = value.get("one_of")
range = value.get("range")
- if eq:
- qs = qs.filter(**{field: eq})
+ if "eq" in value:
+ # allow filtering by `None` value
+ return qs.filter(**{field: value["eq"]})
if one_of:
- qs = qs.filter(**{f"{field}__in": one_of})
+ return qs.filter(**{f"{field}__in": one_of})
if range and isinstance(range, dict):
lte = range.get("lte")
gte = range.get("gte")
+ if lte is None and gte is None:
+ return qs.none()
if lte is not None:
qs = qs.filter(**{f"{field}__lte": lte})
if gte is not None:
qs = qs.filter(**{f"{field}__gte": gte})
- return qs
+ return qs
+ return qs.none()