Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend `AttributePageWhereInput` to allow filtering by assigned references (#17967)
Maciej Korycinski836d01d8429f
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.pyindex 4fef743893..87377cce4d 100644--- a/saleor/graphql/attribute/filters.py+++ b/saleor/graphql/attribute/filters.py@@ -1,12 +1,15 @@+from typing import Literal, TypedDict+import django_filtersimport graphene-from django.db.models import Q+from django.db.models import Exists, OuterRef, Q, QuerySetfrom ...attribute import AttributeInputType-from ...attribute.models import Attribute, AttributeValue+from ...attribute.models import AssignedPageAttributeValue, Attribute, AttributeValuefrom ...channel.models import Channel+from ...page import models as page_modelsfrom ...permission.utils import has_one_of_permissions-from ...product import models+from ...product import models as product_modelsfrom ...product.models import ALL_PRODUCTS_PERMISSIONSfrom ..channel.filters import get_channel_slug_from_filter_datafrom ..core.doc_category import DOC_CATEGORY_ATTRIBUTES@@ -31,10 +34,8 @@ from ..core.filters.where_input import (StringFilterInput,WhereInputObjectType,)-from ..core.types import (- BaseInputObjectType,- NonNullList,-)+from ..core.types.base import BaseInputObjectType+from ..core.types.common import NonNullListfrom ..core.utils import from_global_id_or_errorfrom ..utils import get_user_or_app_from_contextfrom ..utils.filters import filter_by_ids, filter_slug_list, filter_where_by_value_field@@ -49,13 +50,15 @@ def filter_attributes_by_product_types(qs, field, value, requestor, channel_slugif channel_slug is not None:channel = Channel.objects.using(qs.db).filter(slug=str(channel_slug)).first()limited_channel_access = False if channel_slug is None else True- product_qs = models.Product.objects.using(qs.db).visible_to_user(+ product_qs = product_models.Product.objects.using(qs.db).visible_to_user(requestor, channel, limited_channel_access)if field == "in_category":_type, category_id = from_global_id_or_error(value, "Category")- category = models.Category.objects.using(qs.db).filter(pk=category_id).first()+ category = (+ product_models.Category.objects.using(qs.db).filter(pk=category_id).first()+ )if category is None:return qs.none()@@ -330,3 +333,352 @@ class AttributeValueWhereInput(WhereInputObjectType):filterset_class = AttributeValueWheredescription = "Where filtering options for attribute values."doc_category = DOC_CATEGORY_ATTRIBUTES+++CONTAINS_TYPING = dict[Literal["contains_any", "contains_all"], list[str]]+++class SharedContainsFilterParams(TypedDict):+ attr_id: int | None+ db_connection_name: str+ assigned_attr_model: type[AssignedPageAttributeValue]+ assigned_id_field_name: Literal["page_id"]+ identifier_field_name: Literal["slug", "id", "sku"]+++def filter_by_contains_referenced_object_ids(+ attr_id: int | None,+ attr_value: CONTAINS_TYPING,+ db_connection_name: str,+ assigned_attr_model: type[AssignedPageAttributeValue],+ assigned_id_field_name: Literal["page_id"],+):+ """Build a filter expression for objects referencing other entities by global IDs.++ Returns a Q expression to filter objects based on their references+ to other entities (like: variants, products, pages), identified by+ global IDs.++ - If `contains_all` is provided, only objects that reference all of the+ specified global IDs will match.+ - If `contains_any` is provided, objects that reference at least one of+ the specified global IDs will match.+ """++ contains_all = attr_value.get("contains_all")+ contains_any = attr_value.get("contains_any")++ variant_ids = set()+ product_ids = set()+ page_ids = set()++ for obj_id in contains_any or contains_all or []:+ type_, id_ = graphene.Node.from_global_id(obj_id)+ if type_ == "Page":+ page_ids.add(id_)+ elif type_ == "Product":+ product_ids.add(id_)+ elif type_ == "ProductVariant":+ variant_ids.add(id_)++ expression = Q()+ shared_filter_params: SharedContainsFilterParams = {+ "attr_id": attr_id,+ "db_connection_name": db_connection_name,+ "assigned_attr_model": assigned_attr_model,+ "assigned_id_field_name": assigned_id_field_name,+ "identifier_field_name": "id",+ }+ if contains_all:+ if page_ids:+ expression &= _filter_contains_all_condition(+ contains_all=list(page_ids),+ referenced_model=page_models.Page,+ attr_value_reference_field_name="reference_page_id",+ **shared_filter_params,+ )+ if product_ids:+ expression &= _filter_contains_all_condition(+ contains_all=list(product_ids),+ referenced_model=product_models.Product,+ attr_value_reference_field_name="reference_product_id",+ **shared_filter_params,+ )+ if variant_ids:+ expression &= _filter_contains_all_condition(+ contains_all=list(variant_ids),+ referenced_model=product_models.ProductVariant,+ attr_value_reference_field_name="reference_variant_id",+ **shared_filter_params,+ )+ return expression++ if contains_any:+ if page_ids:+ expression |= _filter_contains_any_condition(+ contains_any=list(page_ids),+ referenced_model=page_models.Page,+ attr_value_reference_field_name="reference_page_id",+ **shared_filter_params,+ )++ if product_ids:+ expression |= _filter_contains_any_condition(+ contains_any=list(product_ids),+ referenced_model=product_models.Product,+ attr_value_reference_field_name="reference_product_id",+ **shared_filter_params,+ )++ if variant_ids:+ expression |= _filter_contains_any_condition(+ contains_any=list(variant_ids),+ referenced_model=product_models.ProductVariant,+ attr_value_reference_field_name="reference_variant_id",+ **shared_filter_params,+ )+ return expression+++def _filter_contains_single_expression(+ attr_id: int | None,+ db_connection_name: str,+ reference_objs: QuerySet[+ page_models.Page | product_models.Product | product_models.ProductVariant+ ],+ attr_value_reference_field_name: Literal[+ "reference_page_id", "reference_product_id", "reference_variant_id"+ ],+ assigned_attr_model: type[AssignedPageAttributeValue],+ assigned_id_field_name: Literal["page_id"],+):+ single_reference_qs = AttributeValue.objects.using(db_connection_name).filter(+ Exists(reference_objs.filter(id=OuterRef(attr_value_reference_field_name))),+ )+ if attr_id:+ attr_query = Attribute.objects.using(db_connection_name).filter(id=attr_id)+ single_reference_qs = single_reference_qs.filter(+ Exists(attr_query.filter(id=OuterRef("attribute_id"))),+ )+ assigned_attr_value = assigned_attr_model.objects.using(db_connection_name).filter(+ Exists(single_reference_qs.filter(id=OuterRef("value_id"))),+ **{str(assigned_id_field_name): OuterRef("id")},+ )+ return Q(Exists(assigned_attr_value))+++def _filter_contains_all_condition(+ attr_id: int | None,+ db_connection_name: str,+ contains_all: list[str],+ assigned_attr_model: type[AssignedPageAttributeValue],+ assigned_id_field_name: Literal["page_id"],+ identifier_field_name: Literal["slug", "id", "sku"],+ referenced_model: type[+ page_models.Page | product_models.Product | product_models.ProductVariant+ ],+ attr_value_reference_field_name: Literal[+ "reference_page_id", "reference_product_id", "reference_variant_id"+ ],+):+ """Build a filter expression that ensures all specified references are present.++ Constructs a Q expression that checks for references to all entities from+ `referenced_model`, matched using the provided identifiers in `contains_all`.++ For each identifier, it resolves the corresponding object using+ `identifier_field_name` and adds a subquery to verify the presence+ of that reference. The subqueries are combined using logical AND.+ """++ identifiers = contains_all+ expression = Q()++ for identifier in identifiers:+ reference_obj = referenced_model.objects.using(db_connection_name).filter(+ **{str(identifier_field_name): identifier}+ )+ expression &= _filter_contains_single_expression(+ attr_id,+ db_connection_name,+ reference_obj,+ attr_value_reference_field_name,+ assigned_attr_model,+ assigned_id_field_name,+ )+ return expression+++def _filter_contains_any_condition(+ attr_id: int | None,+ db_connection_name: str,+ contains_any: list[str],+ assigned_attr_model: type[AssignedPageAttributeValue],+ assigned_id_field_name: Literal["page_id"],+ identifier_field_name: Literal["slug", "id", "sku"],+ referenced_model: type[+ page_models.Page | product_models.Product | product_models.ProductVariant+ ],+ attr_value_reference_field_name: Literal[+ "reference_page_id", "reference_product_id", "reference_variant_id"+ ],+):+ """Build a filter expression that ensures at least one specified reference is present.++ Constructs a Q expression that checks for a reference to any entity from+ `referenced_model`, matched using the provided identifiers in `contains_any`.++ All matching references are resolved using `identifier_field_name`,+ and passed as a single queryset to be checked in a single subquery.++ """+ identifiers = contains_any+ reference_objs = referenced_model.objects.using(db_connection_name).filter(+ **{f"{identifier_field_name}__in": identifiers}+ )+ return _filter_contains_single_expression(+ attr_id,+ db_connection_name,+ reference_objs,+ attr_value_reference_field_name,+ assigned_attr_model,+ assigned_id_field_name,+ )+++def filter_by_contains_referenced_pages(+ attr_id: int | None,+ attr_value: CONTAINS_TYPING,+ db_connection_name: str,+ assigned_attr_model: type[AssignedPageAttributeValue],+ assigned_id_field_name: Literal["page_id"],+):+ """Build a filter expression for referenced pages.++ Returns a Q expression to filter objects based on their references+ to pages.++ - If `contains_all` is provided, only objects that reference all of the+ specified pages will match.+ - If `contains_any` is provided, objects that reference at least one of+ the specified pages will match.+ """+ contains_all = attr_value.get("contains_all")+ contains_any = attr_value.get("contains_any")++ shared_filter_params: SharedContainsFilterParams = {+ "attr_id": attr_id,+ "db_connection_name": db_connection_name,+ "assigned_attr_model": assigned_attr_model,+ "assigned_id_field_name": assigned_id_field_name,+ "identifier_field_name": "slug",+ }+ if contains_all:+ return _filter_contains_all_condition(+ contains_all=contains_all,+ referenced_model=page_models.Page,+ attr_value_reference_field_name="reference_page_id",+ **shared_filter_params,+ )++ if contains_any:+ return _filter_contains_any_condition(+ contains_any=contains_any,+ referenced_model=page_models.Page,+ attr_value_reference_field_name="reference_page_id",+ **shared_filter_params,+ )+ return Q()+++def filter_by_contains_referenced_products(+ attr_id: int | None,+ attr_value: CONTAINS_TYPING,+ db_connection_name: str,+ assigned_attr_model: type[AssignedPageAttributeValue],+ assigned_id_field_name: Literal["page_id"],+):+ """Build a filter expression for referenced products.++ Returns a Q expression to filter objects based on their references+ to products.++ - If `contains_all` is provided, only objects that reference all of the+ specified products will match.+ - If `contains_any` is provided, objects that reference at least one of+ the specified products will match.+ """+ contains_all = attr_value.get("contains_all")+ contains_any = attr_value.get("contains_any")++ shared_filter_params: SharedContainsFilterParams = {+ "attr_id": attr_id,+ "db_connection_name": db_connection_name,+ "assigned_attr_model": assigned_attr_model,+ "assigned_id_field_name": assigned_id_field_name,+ "identifier_field_name": "slug",+ }++ if contains_all:+ return _filter_contains_all_condition(+ contains_all=contains_all,+ referenced_model=product_models.Product,+ attr_value_reference_field_name="reference_product_id",+ **shared_filter_params,+ )++ if contains_any:+ return _filter_contains_any_condition(+ contains_any=contains_any,+ referenced_model=product_models.Product,+ attr_value_reference_field_name="reference_product_id",+ **shared_filter_params,+ )+ return Q()+++def filter_by_contains_referenced_variants(+ attr_id: int | None,+ attr_value: CONTAINS_TYPING,+ db_connection_name: str,+ assigned_attr_model: type[AssignedPageAttributeValue],+ assigned_id_field_name: Literal["page_id"],+):+ """Build a filter expression for referenced product variants.++ Returns a Q expression to filter objects based on their references+ to product variants.++ - If `contains_all` is provided, only objects that reference all of the+ specified variants will match.+ - If `contains_any` is provided, objects that reference at least one of+ the specified variants will match.+ """++ contains_all = attr_value.get("contains_all")+ contains_any = attr_value.get("contains_any")++ shared_filter_params: SharedContainsFilterParams = {+ "attr_id": attr_id,+ "db_connection_name": db_connection_name,+ "assigned_attr_model": assigned_attr_model,+ "assigned_id_field_name": assigned_id_field_name,+ "identifier_field_name": "sku",+ }++ if contains_all:+ return _filter_contains_all_condition(+ contains_all=contains_all,+ referenced_model=product_models.ProductVariant,+ attr_value_reference_field_name="reference_variant_id",+ **shared_filter_params,+ )++ if contains_any:+ return _filter_contains_any_condition(+ contains_any=contains_any,+ referenced_model=product_models.ProductVariant,+ attr_value_reference_field_name="reference_variant_id",+ **shared_filter_params,+ )+ return Q()diff --git a/saleor/graphql/core/filters/where_input.py b/saleor/graphql/core/filters/where_input.pyindex 0b48daa8df..ff642ef37b 100644--- a/saleor/graphql/core/filters/where_input.py+++ b/saleor/graphql/core/filters/where_input.py@@ -56,6 +56,8 @@ class FilterInputDescriptions:ONE_OF = "The value included in."NOT_ONE_OF = "The value not included in."RANGE = "The value in range."+ CONTAINS_ALL = "The field contains all of the specified values."+ CONTAINS_ANY = "The field contains at least one of the specified values."class StringFilterInput(graphene.InputObjectType):@@ -182,3 +184,21 @@ class MetadataFilterInput(graphene.InputObjectType):- `{key: "status", value: {eq: "active"}}`Matches objects where the metadata key "status" is set to "active"."""+++class ContainsFilterInput(graphene.InputObjectType):+ contains_any = NonNullList(+ graphene.String,+ description=FilterInputDescriptions.CONTAINS_ANY,+ required=False,+ )+ contains_all = NonNullList(+ graphene.String,+ description=FilterInputDescriptions.CONTAINS_ALL,+ required=False,+ )++ class Meta:+ description = (+ "Define the filtering options for fields that can contain multiple values."+ )diff --git a/saleor/graphql/page/filters.py b/saleor/graphql/page/filters.pyindex 2316af92fa..516e7bd582 100644--- a/saleor/graphql/page/filters.py+++ b/saleor/graphql/page/filters.py@@ -1,3 +1,5 @@+from typing import Literal+import django_filtersimport graphenefrom django.db.models import Exists, FloatField, OuterRef, Q@@ -7,6 +9,13 @@ from graphql import GraphQLErrorfrom ...attribute import AttributeInputTypefrom ...attribute.models import AssignedPageAttributeValue, Attribute, AttributeValuefrom ...page import models+from ..attribute.filters import (+ CONTAINS_TYPING,+ filter_by_contains_referenced_object_ids,+ filter_by_contains_referenced_pages,+ filter_by_contains_referenced_products,+ filter_by_contains_referenced_variants,+)from ..core.context import ChannelQsContextfrom ..core.doc_category import DOC_CATEGORY_PAGESfrom ..core.filters import (@@ -22,6 +31,7 @@ from ..core.filters.where_filters import (OperationObjectTypeWhereFilter,)from ..core.filters.where_input import (+ ContainsFilterInput,DecimalFilterInput,GlobalIDFilterInput,StringFilterInput,@@ -212,16 +222,128 @@ def filter_pages_by_attributes(qs, value):attr_filter_expression &= filter_by_date_time_attribute(attr.id, attr_value["date_time"], qs.db)+ elif attr.input_type == AttributeInputType.REFERENCE:+ attr_filter_expression &= filter_pages_by_reference_attributes(+ attr.id, attr_value["reference"], qs.db+ )if attr_filter_expression != Q():return qs.filter(attr_filter_expression)return qs.none()+def filter_pages_by_reference_attributes(+ attr_id: int | None,+ attr_value: dict[+ Literal[+ "referenced_ids", "page_slugs", "product_slugs", "product_variant_skus"+ ],+ CONTAINS_TYPING,+ ],+ db_connection_name: str,+):+ filter_expression = Q()++ if "referenced_ids" in attr_value:+ filter_expression &= filter_by_contains_referenced_object_ids(+ attr_id,+ attr_value["referenced_ids"],+ db_connection_name,+ assigned_attr_model=AssignedPageAttributeValue,+ assigned_id_field_name="page_id",+ )+ if "page_slugs" in attr_value:+ filter_expression &= filter_by_contains_referenced_pages(+ attr_id,+ attr_value["page_slugs"],+ db_connection_name,+ assigned_attr_model=AssignedPageAttributeValue,+ assigned_id_field_name="page_id",+ )+ if "product_slugs" in attr_value:+ filter_expression &= filter_by_contains_referenced_products(+ attr_id,+ attr_value["product_slugs"],+ db_connection_name,+ assigned_attr_model=AssignedPageAttributeValue,+ assigned_id_field_name="page_id",+ )+ if "product_variant_skus" in attr_value:+ filter_expression &= filter_by_contains_referenced_variants(+ attr_id,+ attr_value["product_variant_skus"],+ db_connection_name,+ assigned_attr_model=AssignedPageAttributeValue,+ assigned_id_field_name="page_id",+ )+ return filter_expression+++def validate_attribute_value_reference_input(+ values: list[+ dict[+ Literal[+ "referenced_ids", "page_slugs", "product_slugs", "product_variant_skus"+ ],+ CONTAINS_TYPING,+ ]+ | None+ ],+):+ """Validate the input for reference attributes.++ This function checks if the input for reference attributes is valid.+ It raises a GraphQLError if the input is invalid.+ """+ duplicated_error = []+ empty_input_value_error = set()+ for value in values:+ if not value:+ raise GraphQLError(+ message="Invalid input for reference attributes. "+ "Provided 'value' cannot be null or empty."+ )+ for key in value:+ single_key_value = value[key]+ if (+ "contains_all" in single_key_value+ and "contains_any" in single_key_value+ ):+ duplicated_error.append(key)+ continue+ if (+ "contains_all" in single_key_value+ and not single_key_value["contains_all"]+ ):+ empty_input_value_error.add(key)+ continue+ if (+ "contains_any" in single_key_value+ and not single_key_value["contains_any"]+ ):+ empty_input_value_error.add(key)++ if empty_input_value_error:+ raise GraphQLError(+ message=(+ f"Invalid input for reference attributes. For fields: {', '.join(empty_input_value_error)}. "+ f"Provided values cannot be null or empty."+ )+ )+ if duplicated_error:+ raise GraphQLError(+ message=(+ f"Invalid input for reference attributes. For fields: {', '.join(duplicated_error)}. "+ "Cannot provide both 'containsAll' and 'containsAny' for the same reference filter."+ )+ )++def validate_attribute_value_input(attributes: list[dict], db_connection_name: str):slug_list = [attr["slug"] for attr in attributes]value_as_empty_list = []value_more_than_one_list = []invalid_input_type_list = []+ reference_value_list = []if len(slug_list) != len(set(slug_list)):raise GraphQLError(message="Duplicated attribute slugs in attribute 'where' input are not allowed."@@ -245,6 +367,8 @@ def validate_attribute_value_input(attributes: list[dict], db_connection_name: sif value[value_key] is None:value_as_empty_list.append(attr["slug"])continue+ if value_key == "reference":+ reference_value_list.append(value["reference"])if type_specific_value_list:attribute_input_type_map = Attribute.objects.using(db_connection_name).in_bulk(@@ -265,6 +389,10 @@ def validate_attribute_value_input(attributes: list[dict], db_connection_name: sinvalid_input_type_list.append(attr_slug)if "boolean" == value_key and input_type != AttributeInputType.BOOLEAN:invalid_input_type_list.append(attr_slug)+ if "reference" == value_key and input_type != AttributeInputType.REFERENCE:+ invalid_input_type_list.append(attr_slug)++ validate_attribute_value_reference_input(reference_value_list)if value_as_empty_list:raise GraphQLError(@@ -289,6 +417,26 @@ def validate_attribute_value_input(attributes: list[dict], db_connection_name: s)+class ReferenceAttributeWhereInput(BaseInputObjectType):+ referenced_ids = ContainsFilterInput(+ description="Returns objects with a reference pointing to an object identified by the given ID.",+ )+ page_slugs = ContainsFilterInput(+ description="Returns objects with a reference pointing to a page identified by the given slug.",+ )+ product_slugs = ContainsFilterInput(+ description=(+ "Returns objects with a reference pointing to a product identified by the given slug."+ )+ )+ product_variant_skus = ContainsFilterInput(+ description=(+ "Returns objects with a reference pointing "+ "to a product variant identified by the given sku."+ )+ )++class AttributeValuePageInput(BaseInputObjectType):slug = StringFilterInput(description="Filter by slug assigned to AttributeValue.",@@ -312,6 +460,10 @@ class AttributeValuePageInput(BaseInputObjectType):required=False,description="Filter by boolean value for attributes of boolean type.",)+ reference = ReferenceAttributeWhereInput(+ required=False,+ description=("Filter by reference attribute value."),+ )class AttributePageWhereInput(BaseInputObjectType):diff --git a/saleor/graphql/page/tests/queries/test_pages.py b/saleor/graphql/page/tests/queries/test_pages.pyindex e983e9be15..72afc39878 100644--- a/saleor/graphql/page/tests/queries/test_pages.py+++ b/saleor/graphql/page/tests/queries/test_pages.py@@ -141,7 +141,7 @@ def test_pages_query_with_filter_by_page_type([({"slugs": ["test-url-1"]}, 1),({"slugs": ["test-url-1", "test-url-2"]}, 2),- ({"slugs": []}, 2),+ ({"slugs": []}, 4),],)def test_pages_with_filtering(filter_by, pages_count, staff_api_client, page_list):diff --git a/saleor/graphql/page/tests/queries/test_pages_with_where.py b/saleor/graphql/page/tests/queries/test_pages_with_where.pyindex 3e8fd9c2ac..2c8b2da1c0 100644--- a/saleor/graphql/page/tests/queries/test_pages_with_where.py+++ b/saleor/graphql/page/tests/queries/test_pages_with_where.py@@ -4,8 +4,10 @@ import grapheneimport pytestfrom .....attribute import AttributeInputType+from .....attribute.models import AttributeValuefrom .....attribute.utils import associate_attribute_values_to_instancefrom .....page.models import Page, PageType+from ....core.utils import to_global_id_or_nonefrom ....tests.utils import get_graphql_contentQUERY_PAGES_WITH_WHERE = """@@ -600,6 +602,638 @@ def test_pages_query_with_attribute_value_boolean()+ ("filter_type", "expected_count"), [("containsAny", 2), ("containsAll", 1)]+)+def test_pages_query_with_attribute_value_reference_to_pages(+ filter_type,+ expected_count,+ staff_api_client,+ page_list,+ page_type,+ page_type_page_reference_attribute,+):+ # given+ page_type.page_attributes.add(page_type_page_reference_attribute)++ reference_page_1_slug = "referenced-page-1"+ reference_page_2_slug = "referenced-page-2"+ referenced_page_1, referenced_page_2 = Page.objects.bulk_create(+ [+ Page(+ title="Referenced Page 1",+ slug=reference_page_1_slug,+ page_type=page_type,+ is_published=True,+ ),+ Page(+ title="Referenced Page 2",+ slug=reference_page_2_slug,+ page_type=page_type,+ is_published=True,+ ),+ ]+ )++ attribute_value_1, attribute_value_2 = AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_type_page_reference_attribute,+ name=f"Page {referenced_page_1.pk}",+ slug=f"page-{referenced_page_1.pk}",+ reference_page=referenced_page_1,+ ),+ AttributeValue(+ attribute=page_type_page_reference_attribute,+ name=f"Page {referenced_page_2.pk}",+ slug=f"page-{referenced_page_2.pk}",+ reference_page=referenced_page_2,+ ),+ ]+ )+ page_with_both_references = page_list[0]+ associate_attribute_values_to_instance(+ page_with_both_references,+ {page_type_page_reference_attribute.pk: [attribute_value_1, attribute_value_2]},+ )++ page_with_single_reference = page_list[1]+ associate_attribute_values_to_instance(+ page_with_single_reference,+ {page_type_page_reference_attribute.pk: [attribute_value_2]},+ )++ variables = {+ "where": {+ "attributes": [+ {+ "slug": "page-reference",+ "value": {+ "reference": {+ "pageSlugs": {+ filter_type: [+ reference_page_1_slug,+ reference_page_2_slug,+ ]+ }+ }+ },+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PAGES_WITH_WHERE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ pages_nodes = content["data"]["pages"]["edges"]+ assert len(pages_nodes) == expected_count+++ ("filter_type", "expected_count"), [("containsAny", 2), ("containsAll", 1)]+)+def test_pages_query_with_attribute_value_reference_to_products(+ filter_type,+ expected_count,+ staff_api_client,+ page_list,+ page_type,+ page_type_product_reference_attribute,+ product_list,+):+ # given+ page_type.page_attributes.add(page_type_product_reference_attribute)++ first_product = product_list[0]+ second_product = product_list[1]++ attribute_value_1, attribute_value_2 = AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {first_product.pk}",+ slug=f"product-{first_product.pk}",+ reference_product=first_product,+ ),+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {second_product.pk}",+ slug=f"product-{second_product.pk}",+ reference_product=second_product,+ ),+ ]+ )++ page_with_both_references = page_list[0]+ associate_attribute_values_to_instance(+ page_with_both_references,+ {+ page_type_product_reference_attribute.pk: [+ attribute_value_1,+ attribute_value_2,+ ]+ },+ )++ page_with_single_reference = page_list[1]+ associate_attribute_values_to_instance(+ page_with_single_reference,+ {page_type_product_reference_attribute.pk: [attribute_value_2]},+ )++ variables = {+ "where": {+ "attributes": [+ {+ "slug": "product-reference",+ "value": {+ "reference": {+ "productSlugs": {+ filter_type: [first_product.slug, second_product.slug]+ }+ }+ },+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PAGES_WITH_WHERE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ pages_nodes = content["data"]["pages"]["edges"]+ assert len(pages_nodes) == expected_count+ assert pages_nodes[0]["node"]["id"] == graphene.Node.to_global_id(+ "Page", page_list[0].pk+ )+++ ("filter_type", "expected_count"), [("containsAny", 2), ("containsAll", 1)]+)+def test_pages_query_with_attribute_value_reference_to_product_variants(+ filter_type,+ expected_count,+ staff_api_client,+ page_list,+ page_type,+ page_type_variant_reference_attribute,+ product_variant_list,+):+ # given+ page_type.page_attributes.add(page_type_variant_reference_attribute)++ first_variant_sku = "test-variant-1"+ second_variant_sku = "test-variant-2"++ first_variant = product_variant_list[0]+ first_variant.sku = first_variant_sku+ first_variant.save()++ second_variant = product_variant_list[1]+ second_variant.sku = second_variant_sku+ second_variant.save()++ attribute_value_1, attribute_value_2 = AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_type_variant_reference_attribute,+ name=f"Variant {first_variant.pk}",+ slug=f"variant-{first_variant.pk}",+ reference_variant=first_variant,+ ),+ AttributeValue(+ attribute=page_type_variant_reference_attribute,+ name=f"Variant {second_variant.pk}",+ slug=f"variant-{second_variant.pk}",+ reference_variant=second_variant,+ ),+ ]+ )++ page_with_both_references = page_list[0]+ associate_attribute_values_to_instance(+ page_with_both_references,+ {+ page_type_variant_reference_attribute.pk: [+ attribute_value_1,+ attribute_value_2,+ ]+ },+ )++ page_with_single_reference = page_list[1]+ associate_attribute_values_to_instance(+ page_with_single_reference,+ {page_type_variant_reference_attribute.pk: [attribute_value_2]},+ )++ variables = {+ "where": {+ "attributes": [+ {+ "slug": "variant-reference",+ "value": {+ "reference": {+ "productVariantSkus": {+ filter_type: [+ first_variant_sku,+ second_variant_sku,+ ]+ }+ }+ },+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PAGES_WITH_WHERE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ pages_nodes = content["data"]["pages"]["edges"]+ assert len(pages_nodes) == expected_count+ assert pages_nodes[0]["node"]["id"] == graphene.Node.to_global_id(+ "Page", page_list[0].pk+ )+++ ("filter_type", "expected_count"), [("containsAny", 3), ("containsAll", 2)]+)+def test_pages_query_with_attribute_value_referenced_page_ids(+ filter_type,+ expected_count,+ staff_api_client,+ page_list,+ page_type,+ page_type_page_reference_attribute,+):+ # given+ page_type.page_attributes.add(+ page_type_page_reference_attribute,+ )++ referenced_first_page, referenced_second_page, referenced_third_page = (+ Page.objects.bulk_create(+ [+ Page(+ title="Referenced Page",+ slug="referenced-page",+ page_type=page_type,+ is_published=True,+ ),+ Page(+ title="Referenced Page",+ slug="referenced-page2",+ page_type=page_type,+ is_published=True,+ ),+ Page(+ title="Referenced Page",+ slug="referenced-page3",+ page_type=page_type,+ is_published=True,+ ),+ ]+ )+ )++ first_attr_value, second_attr_value, third_attr_value = (+ AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_type_page_reference_attribute,+ name=f"Page {referenced_first_page.pk}",+ slug=f"page-{referenced_first_page.pk}",+ reference_page=referenced_first_page,+ ),+ AttributeValue(+ attribute=page_type_page_reference_attribute,+ name=f"Page {referenced_second_page.pk}",+ slug=f"page-{referenced_second_page.pk}",+ reference_page=referenced_second_page,+ ),+ AttributeValue(+ attribute=page_type_page_reference_attribute,+ name=f"Page {referenced_third_page.pk}",+ slug=f"page-{referenced_third_page.pk}",+ reference_page=referenced_third_page,+ ),+ ]+ )+ )+ fist_page_with_all_ids = page_list[0]+ second_page_with_all_ids = page_list[1]+ page_with_single_id = page_list[2]+ associate_attribute_values_to_instance(+ fist_page_with_all_ids,+ {+ page_type_page_reference_attribute.pk: [+ first_attr_value,+ second_attr_value,+ third_attr_value,+ ],+ },+ )++ associate_attribute_values_to_instance(+ second_page_with_all_ids,+ {+ page_type_page_reference_attribute.pk: [+ first_attr_value,+ second_attr_value,+ third_attr_value,+ ],+ },+ )++ associate_attribute_values_to_instance(+ page_with_single_id,+ {page_type_page_reference_attribute.pk: [first_attr_value]},+ )++ referenced_first_global_id = to_global_id_or_none(referenced_first_page)+ referenced_second_global_id = to_global_id_or_none(referenced_second_page)+ referenced_third_global_id = to_global_id_or_none(referenced_third_page)++ variables = {+ "where": {+ "attributes": [+ {+ "slug": page_type_page_reference_attribute.slug,+ "value": {+ "reference": {+ "referencedIds": {+ filter_type: [+ referenced_first_global_id,+ referenced_second_global_id,+ referenced_third_global_id,+ ]+ }+ }+ },+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PAGES_WITH_WHERE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ pages_nodes = content["data"]["pages"]["edges"]+ assert len(page_list) > len(pages_nodes)+ assert len(pages_nodes) == expected_count+++ ("filter_type", "expected_count"), [("containsAny", 3), ("containsAll", 2)]+)+def test_pages_query_with_attribute_value_referenced_variant_ids(+ filter_type,+ expected_count,+ staff_api_client,+ page_list,+ page_type,+ page_type_variant_reference_attribute,+ product_variant_list,+):+ # given+ page_type.page_attributes.add(+ page_type_variant_reference_attribute,+ )++ first_variant = product_variant_list[0]+ second_variant = product_variant_list[1]+ third_variant = product_variant_list[2]++ first_attr_value, second_attr_value, third_attr_value = (+ AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_type_variant_reference_attribute,+ name=f"Variant {first_variant.pk}",+ slug=f"variant-{first_variant.pk}",+ reference_variant=first_variant,+ ),+ AttributeValue(+ attribute=page_type_variant_reference_attribute,+ name=f"Variant {second_variant.pk}",+ slug=f"variant-{second_variant.pk}",+ reference_variant=second_variant,+ ),+ AttributeValue(+ attribute=page_type_variant_reference_attribute,+ name=f"Variant {third_variant.pk}",+ slug=f"variant-{third_variant.pk}",+ reference_variant=third_variant,+ ),+ ]+ )+ )+ fist_page_with_all_ids = page_list[0]+ second_page_with_all_ids = page_list[1]+ page_with_single_id = page_list[2]+ associate_attribute_values_to_instance(+ fist_page_with_all_ids,+ {+ page_type_variant_reference_attribute.pk: [+ first_attr_value,+ second_attr_value,+ third_attr_value,+ ],+ },+ )++ associate_attribute_values_to_instance(+ second_page_with_all_ids,+ {+ page_type_variant_reference_attribute.pk: [+ first_attr_value,+ second_attr_value,+ third_attr_value,+ ],+ },+ )++ associate_attribute_values_to_instance(+ page_with_single_id,+ {page_type_variant_reference_attribute.pk: [first_attr_value]},+ )+ referenced_first_global_id = to_global_id_or_none(first_variant)+ referenced_second_global_id = to_global_id_or_none(second_variant)+ referenced_third_global_id = to_global_id_or_none(third_variant)++ variables = {+ "where": {+ "attributes": [+ {+ "slug": page_type_variant_reference_attribute.slug,+ "value": {+ "reference": {+ "referencedIds": {+ filter_type: [+ referenced_first_global_id,+ referenced_second_global_id,+ referenced_third_global_id,+ ]+ }+ }+ },+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PAGES_WITH_WHERE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ pages_nodes = content["data"]["pages"]["edges"]+ assert len(page_list) > len(pages_nodes)+ assert len(pages_nodes) == expected_count+++ ("filter_type", "expected_count"), [("containsAny", 3), ("containsAll", 2)]+)+def test_pages_query_with_attribute_value_referenced_product_ids(+ filter_type,+ expected_count,+ staff_api_client,+ page_list,+ page_type,+ page_type_product_reference_attribute,+ product_list,+):+ # given+ page_type.page_attributes.add(+ page_type_product_reference_attribute,+ )+ first_product = product_list[0]+ second_product = product_list[1]+ third_product = product_list[2]++ first_attr_value, second_attr_value, third_attr_value = (+ AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {first_product.pk}",+ slug=f"Product-{first_product.pk}",+ reference_product=first_product,+ ),+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {second_product.pk}",+ slug=f"product-{second_product.pk}",+ reference_product=second_product,+ ),+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {third_product.pk}",+ slug=f"Product-{third_product.pk}",+ reference_product=third_product,+ ),+ ]+ )+ )+ fist_page_with_all_ids = page_list[0]+ second_page_with_all_ids = page_list[1]+ page_with_single_id = page_list[2]+ associate_attribute_values_to_instance(+ fist_page_with_all_ids,+ {+ page_type_product_reference_attribute.pk: [+ first_attr_value,+ second_attr_value,+ third_attr_value,+ ],+ },+ )++ associate_attribute_values_to_instance(+ second_page_with_all_ids,+ {+ page_type_product_reference_attribute.pk: [+ first_attr_value,+ second_attr_value,+ third_attr_value,+ ],+ },+ )++ associate_attribute_values_to_instance(+ page_with_single_id,+ {+ page_type_product_reference_attribute.pk: [+ first_attr_value,+ ],+ },+ )+ referenced_first_global_id = to_global_id_or_none(first_product)+ referenced_second_global_id = to_global_id_or_none(second_product)+ referenced_third_global_id = to_global_id_or_none(third_product)++ variables = {+ "where": {+ "attributes": [+ {+ "slug": page_type_product_reference_attribute.slug,+ "value": {+ "reference": {+ "referencedIds": {+ filter_type: [+ referenced_first_global_id,+ referenced_second_global_id,+ referenced_third_global_id,+ ]+ }+ }+ },+ },+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PAGES_WITH_WHERE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ pages_nodes = content["data"]["pages"]["edges"]+ assert len(page_list) > len(pages_nodes)+ assert len(pages_nodes) == expected_count++@pytest.mark.parametrize("attribute_filter",[@@ -659,6 +1293,158 @@ def test_pages_query_with_attribute_value_boolean([{"slug": "date_time", "value": {"slug": None}}],# Date time can't be used with non date time fields[{"slug": "date_time", "value": {"numeric": {"eq": 1.2}}}],+ # Reference attribute+ [+ {+ "slug": "date_time",+ "value": {+ "reference": {+ "pageSlugs": {+ "containsAll": [+ "about",+ ]+ }+ }+ },+ }+ ],+ [{"slug": "reference-product", "value": {}}],+ [{"slug": "reference-product", "value": {"reference": {}}}],+ [{"slug": "reference-product", "value": {"reference": None}}],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"referencedIds": {"containsAll": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"pageSlugs": {"containsAll": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productSlugs": {"containsAll": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productVariantSkus": {"containsAll": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"pageSlugs": {"containsAny": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productSlugs": {"containsAny": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productVariantSkus": {"containsAny": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"referencedIds": {"containsAny": []}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {+ "reference": {"pageSlugs": {"containsAny": [], "containsAll": []}}+ },+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {+ "reference": {+ "productSlugs": {"containsAny": [], "containsAll": []}+ }+ },+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {+ "reference": {+ "productVariantSkus": {"containsAny": [], "containsAll": []}+ }+ },+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {+ "reference": {+ "referencedIds": {"containsAny": [], "containsAll": []}+ }+ },+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"referencedIds": {"containsAll": None}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"pageSlugs": {"containsAll": None}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productSlugs": {"containsAll": None}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productVariantSkus": {"containsAll": None}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"pageSlugs": {"containsAny": None}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productSlugs": {"containsAny": None}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"productVariantSkus": {"containsAny": None}}},+ }+ ],+ [+ {+ "slug": "reference-product",+ "value": {"reference": {"referencedIds": {"containsAny": None}}},+ }+ ],],)def test_pages_query_failed_filter_validation(@@ -672,6 +1458,7 @@ def test_pages_query_failed_filter_validation(numeric_attribute_without_unit,date_attribute,date_time_attribute,+ page_type_product_reference_attribute,):# givenboolean_attribute.type = "PAGE_TYPE"@@ -679,6 +1466,12 @@ def test_pages_query_failed_filter_validation(numeric_attribute_without_unit.type = "PAGE_TYPE"numeric_attribute_without_unit.save()+ page_type_product_reference_attribute.slug = "reference-product"+ page_type_product_reference_attribute.save()++ page_type.page_attributes.add(+ page_type_product_reference_attribute,+ )page_type.page_attributes.add(size_page_attribute)page_type.page_attributes.add(tag_page_attribute)page_type.page_attributes.add(boolean_attribute)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 10421a2277..98fcbc84e6 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -13034,6 +13034,42 @@ input AttributeValuePageInput {"""Filter by boolean value for attributes of boolean type."""boolean: Boolean++ """Filter by reference attribute value."""+ reference: ReferenceAttributeWhereInput+}++input ReferenceAttributeWhereInput {+ """+ Returns objects with a reference pointing to an object identified by the given ID.+ """+ referencedIds: ContainsFilterInput++ """+ Returns objects with a reference pointing to a page identified by the given slug.+ """+ pageSlugs: ContainsFilterInput++ """+ Returns objects with a reference pointing to a product identified by the given slug.+ """+ productSlugs: ContainsFilterInput++ """+ Returns objects with a reference pointing to a product variant identified by the given sku.+ """+ productVariantSkus: ContainsFilterInput+}++"""+Define the filtering options for fields that can contain multiple values.+"""+input ContainsFilterInput {+ """The field contains at least one of the specified values."""+ containsAny: [String!]++ """The field contains all of the specified values."""+ containsAll: [String!]}type PageTypeCountableConnection @doc(category: "Pages") {diff --git a/saleor/page/tests/fixtures/page.py b/saleor/page/tests/fixtures/page.pyindex f983457f34..22a39b7235 100644--- a/saleor/page/tests/fixtures/page.py+++ b/saleor/page/tests/fixtures/page.py@@ -63,7 +63,23 @@ def page_list(db, page_type):"is_published": True,"page_type": page_type,}- pages = Page.objects.bulk_create([Page(**data_1), Page(**data_2)])+ data_3 = {+ "slug": "test3",+ "title": "Test page3",+ "content": dummy_editorjs("Test content."),+ "is_published": True,+ "page_type": page_type,+ }+ data_4 = {+ "slug": "test4",+ "title": "Test page4",+ "content": dummy_editorjs("Test content."),+ "is_published": True,+ "page_type": page_type,+ }+ pages = Page.objects.bulk_create(+ [Page(**data_1), Page(**data_2), Page(**data_3), Page(**data_4)]+ )return pages