Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add single reference attribute (#17966)
Iga Karbowiak59dc1c0037f3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1f34838b1f..96e237b7fe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -86,6 +86,8 @@ All notable, unreleased changes to this project will be documented in this file.- Filtering products by `category` now also includes subcategories. The filter will return products that belong to the specified categories as well as their subcategories.- Deprecated `Transaction.gatewayResponse` field. Please migrate to Transaction API and Apps.- Extend the `Attribute` type with a `values` field, allowing you to retrieve all values assigned to a specific attribute.+- Add new `single-reference` attribute. You can now create a reference attribute that points to only one object (unlike the existing `reference` type, which supports multiple references).+Like `reference`, the `single-reference` type can target entities defined in the `AttributeEntityTypeEnum`.### Webhooks- Transaction webhooks responsible for processing payments can now return payment method details`, which will be associated with the corresponding transaction. See [docs](https://docs.saleor.io/developer/extending/webhooks/synchronous-events/transaction#response-4) to learn more.diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.pyindex d5e85f36f9..811630bfc2 100644--- a/saleor/attribute/__init__.py+++ b/saleor/attribute/__init__.py@@ -5,6 +5,7 @@ class AttributeInputType:MULTISELECT = "multiselect"FILE = "file"REFERENCE = "reference"+ SINGLE_REFERENCE = "single-reference"NUMERIC = "numeric"RICH_TEXT = "rich-text"PLAIN_TEXT = "plain-text"@@ -18,6 +19,7 @@ class AttributeInputType:(MULTISELECT, "Multi Select"),(FILE, "File"),(REFERENCE, "Reference"),+ (SINGLE_REFERENCE, "Single Reference"),(NUMERIC, "Numeric"),(RICH_TEXT, "Rich Text"),(PLAIN_TEXT, "Plain Text"),diff --git a/saleor/attribute/migrations/0050_alter_attribute_input_type.py b/saleor/attribute/migrations/0050_alter_attribute_input_type.pynew file mode 100644index 0000000000..2e07e8f8eb--- /dev/null+++ b/saleor/attribute/migrations/0050_alter_attribute_input_type.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.1 on 2025-07-09 10:40++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("attribute", "0049_attributevalue_references_attr_entity_type"),+ ]++ operations = [+ migrations.AlterField(+ model_name="attribute",+ name="input_type",+ field=models.CharField(+ choices=[+ ("dropdown", "Dropdown"),+ ("multiselect", "Multi Select"),+ ("file", "File"),+ ("reference", "Reference"),+ ("single-reference", "Single Reference"),+ ("numeric", "Numeric"),+ ("rich-text", "Rich Text"),+ ("plain-text", "Plain Text"),+ ("swatch", "Swatch"),+ ("boolean", "Boolean"),+ ("date", "Date"),+ ("date-time", "Date Time"),+ ],+ default="dropdown",+ max_length=50,+ ),+ ),+ ]diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.pyindex 061faf102b..05c96d76a8 100644--- a/saleor/attribute/tests/fixtures/attribute.py+++ b/saleor/attribute/tests/fixtures/attribute.py@@ -680,6 +680,116 @@ def page_type_collection_reference_attribute(db):)+def product_type_page_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-page-reference",+ name="Single page reference",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.PAGE,+ )+++def page_type_page_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-page-reference",+ name="Single page reference",+ type=AttributeType.PAGE_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.PAGE,+ )+++def product_type_product_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-product-reference",+ name="Single product reference",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.PRODUCT,+ )+++def page_type_product_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-product-reference",+ name="Single product reference",+ type=AttributeType.PAGE_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.PRODUCT,+ )+++def product_type_variant_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-variant-reference",+ name="Single variant reference",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.PRODUCT_VARIANT,+ )+++def page_type_variant_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-variant-reference",+ name="Single variant reference",+ type=AttributeType.PAGE_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.PRODUCT_VARIANT,+ )+++def product_type_category_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-category-reference",+ name="Single category reference",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.CATEGORY,+ )+++def page_type_category_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-category-reference",+ name="Single category reference",+ type=AttributeType.PAGE_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.CATEGORY,+ )+++def product_type_collection_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-collection-reference",+ name="Single collection reference",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.COLLECTION,+ )+++def page_type_collection_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="single-collection-reference",+ name="Single collection reference",+ type=AttributeType.PAGE_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.COLLECTION,+ )++@pytest.fixturedef size_page_attribute(db):attribute = Attribute.objects.create(diff --git a/saleor/graphql/attribute/mutations/attribute_create.py b/saleor/graphql/attribute/mutations/attribute_create.pyindex a51c7a0a16..c694319755 100644--- a/saleor/graphql/attribute/mutations/attribute_create.py+++ b/saleor/graphql/attribute/mutations/attribute_create.py@@ -133,13 +133,15 @@ class AttributeCreate(AttributeMixin, DeprecatedModelMutation):@classmethoddef clean_input(cls, info: ResolveInfo, instance, data, **kwargs):cleaned_input = super().clean_input(info, instance, data, **kwargs)- if cleaned_input.get(- "input_type"- ) == AttributeInputType.REFERENCE and not cleaned_input.get("entity_type"):+ is_reference_type = cleaned_input.get("input_type") in [+ AttributeInputType.REFERENCE,+ AttributeInputType.SINGLE_REFERENCE,+ ]+ if is_reference_type and not cleaned_input.get("entity_type"):raise ValidationError({"entity_type": ValidationError(- "Entity type is required when REFERENCE input type is used.",+ "Entity type is required for reference input type.",code=AttributeErrorCode.REQUIRED.value,)}diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.pyindex fdd1cf81e9..31bc36066f 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py@@ -594,7 +594,12 @@ def test_create_attribute_with_file_input_type(@pytest.mark.parametrize("entity_type",- [AttributeEntityTypeEnum.PAGE.name, AttributeEntityTypeEnum.PRODUCT.name],+ [+ AttributeEntityTypeEnum.PAGE.name,+ AttributeEntityTypeEnum.PRODUCT.name,+ AttributeEntityTypeEnum.COLLECTION.name,+ AttributeEntityTypeEnum.CATEGORY.name,+ ],)def test_create_attribute_with_reference_input_type(entity_type,@@ -684,6 +689,105 @@ def test_create_attribute_with_reference_input_type_entity_type_not_given(assert errors[0]["code"] == AttributeErrorCode.REQUIRED.name+ "entity_type",+ [+ AttributeEntityTypeEnum.PAGE.name,+ AttributeEntityTypeEnum.PRODUCT.name,+ AttributeEntityTypeEnum.COLLECTION.name,+ AttributeEntityTypeEnum.CATEGORY.name,+ ],+)+def test_create_attribute_with_single_reference_input_type(+ entity_type,+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.SINGLE_REFERENCE.name,+ "entityType": entity_type,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["attributeCreate"]["errors"]+ data = content["data"]["attributeCreate"]++ # Check if the attribute was correctly created+ assert data["attribute"]["name"] == attribute_name+ assert data["attribute"]["slug"] == slugify(attribute_name), (+ "The default slug should be the slugified name"+ )+ assert data["attribute"]["productTypes"]["edges"] == [], (+ "The attribute should not have been assigned to a product type"+ )++ # Check if the attribute values were correctly created+ assert len(data["attribute"]["choices"]["edges"]) == 0+ assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name+ assert (+ data["attribute"]["inputType"] == AttributeInputTypeEnum.SINGLE_REFERENCE.name+ )+ assert data["attribute"]["entityType"] == entity_type+++def test_create_attribute_with_single_reference_input_type_entity_type_not_given(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.SINGLE_REFERENCE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["errors"]++ assert not data["attribute"]+ assert len(errors) == 1+ assert errors[0]["field"] == "entityType"+ assert errors[0]["code"] == AttributeErrorCode.REQUIRED.name++def test_create_attribute_with_plain_text_input_type(staff_api_client,permission_manage_product_types_and_attributes,diff --git a/saleor/graphql/attribute/tests/type_handlers/__init__.py b/saleor/graphql/attribute/tests/type_handlers/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/attribute/tests/type_handlers/test_reference_handler.py b/saleor/graphql/attribute/tests/type_handlers/test_reference_handler.pynew file mode 100644index 0000000000..403664f30a--- /dev/null+++ b/saleor/graphql/attribute/tests/type_handlers/test_reference_handler.py@@ -0,0 +1,346 @@+from collections import defaultdict++import graphene+from django.utils.text import slugify+from text_unidecode import unidecode++from ...enums import AttributeValueBulkActionEnum+from ...utils.shared import AttrValuesInput+from ...utils.type_handlers import AttributeInputErrors, ReferenceAttributeHandler+++def test_reference_handler_clean_and_validate_product_reference(+ product_type_product_reference_attribute, product_list+):+ # given+ product_ids = [graphene.Node.to_global_id("Product", p.id) for p in product_list]+ attribute = product_type_product_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ values_input = AttrValuesInput(global_id=attribute_id, references=product_ids)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.references+ assert set(handler.values_input.references) == set(product_list)+++def test_reference_handler_clean_and_validate_page_reference(+ product_type_page_reference_attribute, page_list+):+ # given+ page_ids = [graphene.Node.to_global_id("Page", p.id) for p in page_list]+ attribute = product_type_page_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ values_input = AttrValuesInput(global_id=attribute_id, references=page_ids)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.references+ assert set(handler.values_input.references) == set(page_list)+++def test_reference_handler_clean_and_validate_variant_reference(+ page_type_variant_reference_attribute, product_variant_list+):+ # given+ variant_ids = [+ graphene.Node.to_global_id("ProductVariant", v.id) for v in product_variant_list+ ]+ attribute = page_type_variant_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ values_input = AttrValuesInput(global_id=attribute_id, references=variant_ids)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.references+ assert set(handler.values_input.references) == set(product_variant_list)+++def test_reference_handler_clean_and_validate_category_reference(+ product_type_category_reference_attribute, category_list+):+ # given+ category_ids = [graphene.Node.to_global_id("Category", c.id) for c in category_list]+ attribute = product_type_category_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ values_input = AttrValuesInput(global_id=attribute_id, references=category_ids)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.references+ assert set(handler.values_input.references) == set(category_list)+++def test_reference_handler_clean_and_validate_collection_reference(+ product_type_collection_reference_attribute, collection_list+):+ # given+ collection_ids = [+ graphene.Node.to_global_id("Collection", c.id) for c in collection_list+ ]+ attribute = product_type_collection_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ values_input = AttrValuesInput(global_id=attribute_id, references=collection_ids)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.references+ assert set(handler.values_input.references) == set(collection_list)+++def test_single_reference_handler_clean_and_validate_page_reference(+ product_type_page_single_reference_attribute, page+):+ # given+ attribute = product_type_page_single_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ page_id = graphene.Node.to_global_id("Page", page.id)+ values_input = AttrValuesInput(global_id=attribute_id, reference=page_id)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.reference == page+++def test_single_reference_handler_clean_and_validate_variant_reference(+ product_type_variant_single_reference_attribute, variant+):+ # given+ attribute = product_type_variant_single_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ values_input = AttrValuesInput(global_id=attribute_id, reference=variant_id)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.reference == variant+++def test_single_reference_handler_clean_and_validate_category_reference(+ product_type_category_single_reference_attribute, category+):+ # given+ attribute = product_type_category_single_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ category_id = graphene.Node.to_global_id("Category", category.id)+ values_input = AttrValuesInput(global_id=attribute_id, reference=category_id)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.reference == category+++def test_single_reference_handler_clean_and_validate_collection_reference(+ page_type_collection_single_reference_attribute, collection+):+ # given+ attribute = page_type_collection_single_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ collection_id = graphene.Node.to_global_id("Collection", collection.id)+ values_input = AttrValuesInput(global_id=attribute_id, reference=collection_id)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.reference == collection+++def test_single_reference_handler_clean_and_validate_success(+ product_type_product_single_reference_attribute, product+):+ # given+ attribute = product_type_product_single_reference_attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ product_id = graphene.Node.to_global_id("Product", product.id)+ values_input = AttrValuesInput(global_id=attribute_id, reference=product_id)+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert not attribute_errors+ assert handler.values_input.reference == product+++def test_reference_handler_clean_and_validate_value_required(+ product_type_product_reference_attribute,+):+ # given+ attribute = product_type_product_reference_attribute+ attribute.value_required = True+ attribute.save(update_fields=["value_required"])+ values_input = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", attribute.id), references=[]+ )+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert attribute_errors[AttributeInputErrors.REFERENCE_REQUIRED]+++def test_single_reference_handlers_clean_and_validate_value_required(+ product_type_product_single_reference_attribute,+):+ # given+ attribute = product_type_product_single_reference_attribute+ attribute.value_required = True+ attribute.save(update_fields=["value_required"])+ values_input = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", attribute.id), reference=None+ )+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert attribute_errors[AttributeInputErrors.REFERENCE_REQUIRED]+++def test_reference_handler_clean_and_validate_invalid_reference(+ product_type_product_reference_attribute, product+):+ # given+ attribute = product_type_product_reference_attribute+ values_input = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),+ references=[+ graphene.Node.to_global_id("ProductVariant", product.id),+ graphene.Node.to_global_id("Product", "123"),+ "ABC",+ ],+ )+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE]+++def test_single_reference_handler_clean_and_validate_invalid_reference(+ product_type_product_single_reference_attribute, product+):+ # given+ attribute = product_type_product_single_reference_attribute+ values_input = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),+ reference=graphene.Node.to_global_id("Order", product.id),+ )+ handler = ReferenceAttributeHandler(attribute, values_input)+ attribute_errors = defaultdict(list)++ # when+ handler.clean_and_validate(attribute_errors)++ # then+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE]+++def test_reference_handler_pre_save_value(+ product_type_product_reference_attribute, product_list, product+):+ # given+ attribute = product_type_product_reference_attribute+ values_input = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),+ references=product_list,+ )+ handler = ReferenceAttributeHandler(attribute, values_input)+ instance = product++ # when+ result = handler.pre_save_value(instance)++ # then+ assert len(result) == len(product_list)+ for i, ref_product in enumerate(product_list):+ action, value_data = result[i]+ expected_slug = slugify(unidecode(f"{instance.id}_{ref_product.id}"))++ assert action == AttributeValueBulkActionEnum.GET_OR_CREATE+ assert value_data["attribute"] == attribute+ assert value_data["slug"] == expected_slug+ assert value_data["defaults"]["name"] == ref_product.name+ assert value_data["reference_product"] == ref_product+++def test_single_reference_handler_pre_save_value(+ product_type_product_single_reference_attribute, product_list, product+):+ # given+ attribute = product_type_product_single_reference_attribute+ ref_product = product_list[0]+ values_input = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),+ reference=ref_product,+ )+ handler = ReferenceAttributeHandler(attribute, values_input)+ instance = product++ # when+ result = handler.pre_save_value(instance)++ # then+ assert len(result) == 1+ action, value_data = result[0]+ expected_slug = slugify(unidecode(f"{instance.id}_{ref_product.id}"))++ assert action == AttributeValueBulkActionEnum.GET_OR_CREATE+ assert value_data["attribute"] == attribute+ assert value_data["slug"] == expected_slug+ assert value_data["defaults"]["name"] == ref_product.name+ assert value_data["reference_product"] == ref_productdiff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 73f4a03e3e..cfe08a42af 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -60,7 +60,10 @@ from .utils.shared import ENTITY_TYPE_MAPPINGdef get_reference_pk(attribute, root: models.AttributeValue) -> None | int:- if attribute.input_type != AttributeInputType.REFERENCE:+ if attribute.input_type not in [+ AttributeInputType.REFERENCE,+ AttributeInputType.SINGLE_REFERENCE,+ ]:return Nonereference_field = ENTITY_TYPE_MAPPING[attribute.entity_type].value_fieldreference_pk = getattr(root, f"{reference_field}_id", None)@@ -637,6 +640,12 @@ class AttributeValueInput(BaseInputObjectType):description="URL of the file attribute. Every time, a new value is created.",)content_type = graphene.String(required=False, description="File content type.")+ reference = graphene.ID(+ required=False,+ description=(+ "ID of the referenced entity for single reference attribute." + ADDED_IN_322+ ),+ )references = NonNullList(graphene.ID,description="List of entity IDs that will be used as references.",diff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.pyindex ca26dd1982..3ca82e45db 100644--- a/saleor/graphql/attribute/utils/attribute_assignment.py+++ b/saleor/graphql/attribute/utils/attribute_assignment.py@@ -53,6 +53,7 @@ class AttributeAssignmentMixin:AttributeInputType.MULTISELECT: MultiSelectableAttributeHandler,AttributeInputType.FILE: FileAttributeHandler,AttributeInputType.REFERENCE: ReferenceAttributeHandler,+ AttributeInputType.SINGLE_REFERENCE: ReferenceAttributeHandler,AttributeInputType.RICH_TEXT: RichTextAttributeHandler,AttributeInputType.PLAIN_TEXT: PlainTextAttributeHandler,AttributeInputType.NUMERIC: NumericAttributeHandler,diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.pyindex b38c27641c..7fada3d324 100644--- a/saleor/graphql/attribute/utils/shared.py+++ b/saleor/graphql/attribute/utils/shared.py@@ -36,7 +36,8 @@ class AttrValuesInput:swatch: AttrValuesForSelectableFieldInput | None = Nonemultiselect: list[AttrValuesForSelectableFieldInput] | None = Nonenumeric: str | None = None- references: list[str] | list[page_models.Page] | None = None+ reference: str | None = None+ references: list[str] | None = Nonefile_url: str | None = Nonecontent_type: str | None = Nonerich_text: dict | None = Nonediff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.pyindex d5cd6beb12..73c7902804 100644--- a/saleor/graphql/attribute/utils/type_handlers.py+++ b/saleor/graphql/attribute/utils/type_handlers.py@@ -1,6 +1,7 @@import abcimport datetimeimport re+from collections.abc import Sequencefrom typing import TYPE_CHECKINGfrom django.core.exceptions import ValidationError@@ -402,7 +403,6 @@ class FileAttributeHandler(AttributeTypeHandler):file_url = self.values_input.file_urlif not file_url:return []-# File attributes should be unique per assignment, so we create a new value# unless this exact URL is already assigned to this instance.value = get_assigned_attribute_value_if_exists(@@ -423,14 +423,19 @@ class FileAttributeHandler(AttributeTypeHandler):class ReferenceAttributeHandler(AttributeTypeHandler):- """Handler for Reference attribute type."""+ """Handler for Reference and Single Reference attribute type."""++ def get_references(self) -> Sequence[str | None]:+ if self.attribute.input_type == AttributeInputType.SINGLE_REFERENCE:+ return [self.values_input.reference] if self.values_input.reference else []+ return self.values_input.references or []def clean_and_validate(self, attribute_errors: T_ERROR_DICT):"""Resolve Graphene IDs and then validate the result.Modifies `self.values_input.references` in place."""- references = self.values_input.references+ references = self.get_references()if not references:if self.attribute.value_required:@@ -450,15 +455,18 @@ class ReferenceAttributeHandler(AttributeTypeHandler):ref_instances = get_nodes(references, self.attribute.entity_type, model=entity_data.model)- self.values_input.references = ref_instancesexcept GraphQLError:- self.values_input.references = []attribute_errors[AttributeInputErrors.INVALID_REFERENCE].append(self.attribute_identifier)+ return+ if self.attribute.input_type == AttributeInputType.SINGLE_REFERENCE:+ self.values_input.reference = ref_instances[0] if ref_instances else None+ else:+ self.values_input.references = ref_instancesdef pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:- references = self.values_input.references+ references = self.get_references()entity_type = self.attribute.entity_typeif not references or not entity_type:return []diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.pyindex 9b073038a6..dc2033c52b 100644--- a/saleor/graphql/page/tests/mutations/test_page_create.py+++ b/saleor/graphql/page/tests/mutations/test_page_create.py@@ -67,7 +67,7 @@ def test_page_create_mutation(staff_api_client, permission_manage_pages, page_typage_is_published = Truepage_type_id = graphene.Node.to_global_id("PageType", page_type.pk)- # Default attributes defined in product_type fixture+ # Default attributes defined in page_type fixturetag_attr = page_type.page_attributes.get(name="tag")tag_value_slug = tag_attr.values.first().slugtag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)@@ -129,7 +129,7 @@ def test_page_create_mutation_with_published_at_date() + datetime.timedelta(days=5)page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)- # Default attributes defined in product_type fixture+ # Default attributes defined in page_type fixturetag_attr = page_type.page_attributes.get(name="tag")tag_value_slug = tag_attr.values.first().slugtag_value_name = tag_attr.values.first().name@@ -279,7 +279,7 @@ def test_page_create_mutation_missing_required_attributes(page_is_published = Truepage_type_id = graphene.Node.to_global_id("PageType", page_type.pk)- # Default attributes defined in product_type fixture+ # Default attributes defined in page_type fixturetag_attr = page_type.page_attributes.get(name="tag")tag_value_slug = tag_attr.values.first().slugtag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)@@ -330,7 +330,7 @@ def test_page_create_mutation_empty_attribute_value(page_is_published = Truepage_type_id = graphene.Node.to_global_id("PageType", page_type.pk)- # Default attributes defined in product_type fixture+ # Default attributes defined in page_type fixturetag_attr = page_type.page_attributes.get(name="tag")tag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)@@ -1384,3 +1384,116 @@ def test_create_page_with_collection_reference_attribute(page_type_collection_reference_attribute.refresh_from_db()assert page_type_collection_reference_attribute.values.count() == values_count + 1+++def test_create_page_with_single_reference_attributes(+ staff_api_client,+ permission_manage_pages,+ page_type,+ page_type_page_single_reference_attribute,+ page_type_product_single_reference_attribute,+ page_type_variant_single_reference_attribute,+ page_type_category_single_reference_attribute,+ page_type_collection_single_reference_attribute,+ collection,+ page,+ product,+ categories,+ product_variant_list,+):+ # given+ page_slug = "test-slug"+ page_content = dummy_editorjs("test content", True)+ page_title = "test title"+ page_is_published = True+ page_type = PageType.objects.create(+ name="Test page type 2", slug="test-page-type-2"+ )+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)++ page_type.page_attributes.add(+ page_type_page_single_reference_attribute,+ page_type_product_single_reference_attribute,+ page_type_variant_single_reference_attribute,+ page_type_category_single_reference_attribute,+ page_type_collection_single_reference_attribute,+ )+ references = [+ (page, page_type_page_single_reference_attribute, page.title),+ (product, page_type_product_single_reference_attribute, product.name),+ (+ product_variant_list[0],+ page_type_variant_single_reference_attribute,+ f"{product_variant_list[0].product.name}: {product_variant_list[0].name}",+ ),+ (+ categories[0],+ page_type_category_single_reference_attribute,+ categories[0].name,+ ),+ (+ collection,+ page_type_collection_single_reference_attribute,+ collection.name,+ ),+ ]+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attr.pk),+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ for ref, attr, _name in references+ ]++ variables = {+ "input": {+ "title": page_title,+ "content": page_content,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": attributes,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageCreate"]+ errors = data["errors"]++ assert not errors+ assert data["page"]["title"] == page_title+ assert data["page"]["content"] == page_content+ assert data["page"]["slug"] == page_slug+ assert data["page"]["isPublished"] == page_is_published+ assert data["page"]["pageType"]["id"] == page_type_id+ attributes_data = data["page"]["attributes"]+ assert len(attributes_data) == len(references)+ page_id = data["page"]["id"]+ _, new_page_pk = graphene.Node.from_global_id(page_id)+ expected_attributes_data = [+ {+ "attribute": {+ "slug": attr.slug,+ },+ "values": [+ {+ "slug": f"{new_page_pk}_{ref.id}",+ "date": None,+ "dateTime": None,+ "name": name,+ "file": None,+ "plainText": None,+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ ],+ }+ for ref, attr, name in references+ ]+ for attr_data in attributes_data:+ assert attr_data in expected_attributes_datadiff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.pyindex 20f30ab059..896e0d50f9 100644--- a/saleor/graphql/page/tests/mutations/test_page_update.py+++ b/saleor/graphql/page/tests/mutations/test_page_update.py@@ -1163,6 +1163,14 @@ UPDATE_PAGE_ATTRIBUTES_MUTATION = """idslugname+ reference+ date+ dateTime+ plainText+ file {+ url+ contentType+ }}}}@@ -1307,3 +1315,101 @@ def test_paginate_pages(user_api_client, page, page_type):content = get_graphql_content(response)pages_data = content["data"]["pages"]assert len(pages_data["edges"]) == 2+++def test_update_page_with_single_reference_attributes(+ staff_api_client,+ permission_manage_pages,+ page_list,+ page_type_page_single_reference_attribute,+ page_type_product_single_reference_attribute,+ page_type_variant_single_reference_attribute,+ page_type_category_single_reference_attribute,+ page_type_collection_single_reference_attribute,+ collection,+ product,+ categories,+ product_variant_list,+):+ # given+ page = page_list[0]+ page.page_type.page_attributes.clear()+ page.page_type.page_attributes.add(+ page_type_page_single_reference_attribute,+ page_type_product_single_reference_attribute,+ page_type_variant_single_reference_attribute,+ page_type_category_single_reference_attribute,+ page_type_collection_single_reference_attribute,+ )+ page_ref = page_list[1]+ references = [+ (page_ref, page_type_page_single_reference_attribute, page_ref.title),+ (product, page_type_product_single_reference_attribute, product.name),+ (+ product_variant_list[0],+ page_type_variant_single_reference_attribute,+ f"{product_variant_list[0].product.name}: {product_variant_list[0].name}",+ ),+ (+ categories[0],+ page_type_category_single_reference_attribute,+ categories[0].name,+ ),+ (+ collection,+ page_type_collection_single_reference_attribute,+ collection.name,+ ),+ ]+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attr.pk),+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ for ref, attr, _name in references+ ]++ variables = {+ "id": graphene.Node.to_global_id("Page", page.pk),+ "input": {+ "attributes": attributes,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_PAGE_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_pages],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageUpdate"]+ errors = data["errors"]++ assert not errors+ attributes_data = data["page"]["attributes"]+ assert len(attributes_data) == len(references)+ expected_attributes_data = [+ {+ "attribute": {+ "slug": attr.slug,+ },+ "values": [+ {+ "id": ANY,+ "slug": f"{page.id}_{ref.id}",+ "date": None,+ "dateTime": None,+ "name": name,+ "file": None,+ "plainText": None,+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ ],+ }+ for ref, attr, name in references+ ]+ for attr_data in attributes_data:+ assert attr_data in expected_attributes_datadiff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pyindex 4cb416d8ff..b1e0740663 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -22,7 +22,7 @@ from ...attribute.types import ()from ...attribute.utils.attribute_assignment import AttributeAssignmentMixinfrom ...core.context import ChannelContext-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.enums import ErrorPolicyEnumfrom ...core.fields import JSONString@@ -157,6 +157,12 @@ class BulkAttributeValueInput(BaseInputObjectType):required=False,description="File content type.",)+ reference = graphene.ID(+ description=(+ "ID of the referenced entity for single reference attribute." + ADDED_IN_322+ ),+ required=False,+ )references = NonNullList(graphene.ID,description=("List of entity IDs that will be used as references."),diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex bd6ef11040..4f55a9dcce 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -797,6 +797,84 @@ def test_product_bulk_create_with_attributes(assert get_product_attribute_values(product, color_attr).count() == 1+def test_product_bulk_create_with_single_reference_attributes(+ staff_api_client,+ product_type,+ category,+ page,+ product_type_page_single_reference_attribute,+ description_json,+ permission_manage_products,+):+ # given+ description_json = json.dumps(description_json)+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)++ product_name_1 = "test name 1"+ product_name_2 = "test name 2"+ base_product_slug = "product-test-slug"+ product_charge_taxes = True+ product_tax_rate = "STANDARD"++ attribute = product_type_page_single_reference_attribute+ product_type.product_attributes.clear()+ product_type.product_attributes.add(attribute)+ attr_id = graphene.Node.to_global_id("Attribute", attribute.id)+ reference = graphene.Node.to_global_id("Page", page.pk)++ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_1,+ "slug": f"{base_product_slug}-1",+ "description": description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "weight": 2,+ "attributes": [+ {"id": attr_id, "reference": reference},+ ],+ },+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_2,+ "slug": f"{base_product_slug}-2",+ "description": description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "attributes": [+ {"id": attr_id, "reference": reference},+ ],+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}+ )+ content = get_graphql_content(response)+ data = content["data"]["productBulkCreate"]++ # then+ products = Product.objects.all()++ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert (+ data["results"][0]["product"]["attributes"][0]["attribute"]["slug"]+ == attribute.slug+ )+ assert (+ data["results"][1]["product"]["attributes"][0]["attribute"]["slug"]+ == attribute.slug+ )++def test_product_bulk_create_with_attributes_using_external_refs(staff_api_client,product_type,diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.pyindex 963135babf..33e8276c70 100644--- a/saleor/graphql/product/tests/mutations/test_product_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_create.py@@ -1907,6 +1907,119 @@ def test_create_product_with_collection_reference_attribute()+def test_create_product_with_single_reference_attributes(+ staff_api_client,+ product_type,+ category,+ color_attribute,+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ permission_manage_products,+ page,+ collection,+ categories,+ product_variant_list,+ product,+):+ # given+ query = CREATE_PRODUCT_MUTATION++ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)+ product_name = "test name"+ product_slug = "product-test-slug"++ product_type.product_attributes.add(+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ )+ references = [+ (page, product_type_page_single_reference_attribute, page.title),+ (product, product_type_product_single_reference_attribute, product.name),+ (+ product_variant_list[0],+ product_type_variant_single_reference_attribute,+ f"{product_variant_list[0].product.name}: {product_variant_list[0].name}",+ ),+ (+ categories[0],+ product_type_category_single_reference_attribute,+ categories[0].name,+ ),+ (+ collection,+ product_type_collection_single_reference_attribute,+ collection.name,+ ),+ ]+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attr.pk),+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ for ref, attr, _name in references+ ]++ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": attributes,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]+ assert data["errors"] == []+ assert data["product"]["name"] == product_name+ assert data["product"]["slug"] == product_slug+ assert data["product"]["productType"]["name"] == product_type.name+ assert data["product"]["category"]["name"] == category.name+ assert len(data["product"]["attributes"]) == len(references) + 1++ _, product_id = graphene.Node.from_global_id(data["product"]["id"])+ expected_attributes_data = [+ {"attribute": {"slug": color_attribute.slug}, "values": []}+ ]+ for ref, attr, name in references:+ expected_attributes_data.append(+ {+ "attribute": {"slug": attr.slug},+ "values": [+ {+ "slug": f"{product_id}_{ref.id}",+ "name": name,+ "file": None,+ "richText": None,+ "plainText": None,+ "boolean": None,+ "date": None,+ "dateTime": None,+ "reference": graphene.Node.to_global_id(+ attr.entity_type, ref.pk+ ),+ }+ ],+ }+ )+ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data++def test_create_product_with_product_reference_attribute_values_saved_in_order(staff_api_client,product_type,diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.pyindex 34bb4b65c6..1bda40a17e 100644--- a/saleor/graphql/product/tests/mutations/test_product_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_update.py@@ -1170,6 +1170,105 @@ def test_update_product_with_page_reference_attribute_value(assert product_type_page_reference_attribute.values.count() == values_count + 1+@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_single_reference_attribute_value(+ updated_webhook_mock,+ staff_api_client,+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ product,+ product_type,+ product_variant_list,+ categories,+ collection,+ page,+ permission_manage_products,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attributes = [+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ ]+ product_type.product_attributes.add(*attributes)+ references = [+ (page, product_type_page_single_reference_attribute, page.title),+ (product, product_type_product_single_reference_attribute, product.name),+ (+ product_variant_list[0],+ product_type_variant_single_reference_attribute,+ f"{product_variant_list[0].product.name}: {product_variant_list[0].name}",+ ),+ (+ categories[0],+ product_type_category_single_reference_attribute,+ categories[0].name,+ ),+ (+ collection,+ product_type_collection_single_reference_attribute,+ collection.name,+ ),+ ]+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attr.pk),+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ for ref, attr, _name in references+ ]++ variables = {+ "productId": product_id,+ "input": {"attributes": attributes},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert data["errors"] == []++ attributes_data = data["product"]["attributes"]+ assert len(attributes_data) == product_type.product_attributes.count()++ expected_attributes_data = [+ {+ "attribute": {+ "id": graphene.Node.to_global_id("Attribute", attr.pk),+ "name": attr.name,+ },+ "values": [+ {+ "id": ANY,+ "slug": f"{product.id}_{ref.id}",+ "name": name,+ "file": None,+ "plainText": None,+ "boolean": None,+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ ],+ }+ for ref, attr, name in references+ ]+ for attr_data in expected_attributes_data:+ assert attr_data in attributes_data++def test_update_product_without_supplying_required_product_attribute(staff_api_client, product, permission_manage_products, color_attribute):diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.pyindex 5ba10799c3..0d989de005 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py@@ -741,6 +741,50 @@ def test_product_variant_bulk_create_with_page_reference_attribute(assert product_variant_count + 1 == ProductVariant.objects.count()+def test_product_variant_bulk_create_with_single_reference_attribute(+ staff_api_client,+ product,+ product_type_category_single_reference_attribute,+ permission_manage_products,+ site_settings,+ category,+):+ # given+ product_variant_count = ProductVariant.objects.count()+ attribute = product_type_category_single_reference_attribute+ product.product_type.variant_attributes.add(attribute)+ reference_attr_id = graphene.Node.to_global_id("Attribute", attribute.id)+ reference = graphene.Node.to_global_id("Category", category.pk)+ product_id = graphene.Node.to_global_id("Product", product.pk)++ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": reference_attr_id, "reference": reference}],+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkCreate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ attributes = data["results"][0]["productVariant"]["attributes"]+ assert attributes[-1]["values"][0]["reference"] == reference+ assert product_variant_count + 1 == ProductVariant.objects.count()++def test_product_variant_bulk_create_with_dropdown_attribute(staff_api_client,product,diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.pyindex 7828b7a237..b059c9147d 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py@@ -1323,6 +1323,120 @@ def test_create_variant_with_collection_reference_attribute(created_webhook_mock.assert_called_once_with(product.variants.last())+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")+def test_create_variant_with_single_reference_attributes(+ created_webhook_mock,+ staff_api_client,+ product,+ product_type,+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ page,+ collection,+ categories,+ product_variant_list,+ permission_manage_products,+ warehouse,+):+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)+ sku = "ABC"++ product_type.variant_attributes.clear()+ product_type.variant_attributes.add(+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ )++ references = [+ (page, product_type_page_single_reference_attribute, page.title),+ (product, product_type_product_single_reference_attribute, product.name),+ (+ product_variant_list[0],+ product_type_variant_single_reference_attribute,+ f"{product_variant_list[0].product.name}: {product_variant_list[0].name}",+ ),+ (+ categories[0],+ product_type_category_single_reference_attribute,+ categories[0].name,+ ),+ (+ collection,+ product_type_collection_single_reference_attribute,+ collection.name,+ ),+ ]+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attr.pk),+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ for ref, attr, _name in references+ ]++ stocks = [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),+ "quantity": 20,+ }+ ]++ variables = {+ "input": {+ "product": product_id,+ "sku": sku,+ "stocks": stocks,+ "attributes": attributes,+ "trackInventory": True,+ }+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]++ assert not content["errors"]+ data = content["productVariant"]+ assert data["sku"] == sku+ assert len(data["stocks"]) == 1+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug++ variant_id = data["id"]+ _, variant_pk = graphene.Node.from_global_id(variant_id)++ expected_attributes_data = [+ {+ "attribute": {"slug": attr.slug},+ "values": [+ {+ "slug": f"{variant_pk}_{ref.id}",+ "name": name,+ "file": None,+ "richText": None,+ "plainText": None,+ "boolean": None,+ "date": None,+ "dateTime": None,+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ ],+ }+ for ref, attr, name in references+ ]+ for attr_data in data["attributes"]:+ assert attr_data in expected_attributes_data++ created_webhook_mock.assert_called_once_with(product.variants.get(pk=variant_pk))++@patch("saleor.plugins.manager.PluginsManager.product_variant_created")def test_create_variant_with_numeric_attribute(created_webhook_mock,diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.pyindex 50ca9b4090..c5eb746cfd 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py@@ -2016,6 +2016,109 @@ def test_update_product_variant_with_category_reference_attribute(assert variant_data["attributes"][0]["values"][0]["reference"] == reference+def test_update_product_variant_with_single_reference_attributes(+ staff_api_client,+ product,+ page,+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ permission_manage_products,+ collection,+ product_variant_list,+ categories,+):+ variant = product.variants.first()+ sku = str(uuid4())[:12]+ assert not variant.sku == sku++ product_type = product.product_type+ product_type.variant_attributes.clear()+ product_type.variant_attributes.add(+ product_type_page_single_reference_attribute,+ product_type_product_single_reference_attribute,+ product_type_variant_single_reference_attribute,+ product_type_category_single_reference_attribute,+ product_type_collection_single_reference_attribute,+ )++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ references = [+ (page, product_type_page_single_reference_attribute, page.title),+ (product, product_type_product_single_reference_attribute, product.name),+ (+ product_variant_list[0],+ product_type_variant_single_reference_attribute,+ f"{product_variant_list[0].product.name}: {product_variant_list[0].name}",+ ),+ (+ categories[0],+ product_type_category_single_reference_attribute,+ categories[0].name,+ ),+ (+ collection,+ product_type_collection_single_reference_attribute,+ collection.name,+ ),+ ]+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attr.pk),+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ for ref, attr, _name in references+ ]++ variables = {+ "id": variant_id,+ "sku": sku,+ "attributes": attributes,+ }++ response = staff_api_client.post_graphql(+ QUERY_UPDATE_VARIANT_ATTRIBUTES,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ data = content["data"]["productVariantUpdate"]+ assert not data["errors"]+ variant_data = data["productVariant"]+ assert variant_data+ assert variant_data["sku"] == sku+ attributes_data = variant_data["attributes"]+ assert len(attributes_data) == len(references)+ expected_attributes_data = [+ {+ "attribute": {+ "slug": attr.slug,+ },+ "values": [+ {+ "id": ANY,+ "date": None,+ "dateTime": None,+ "richText": None,+ "slug": f"{variant.id}_{ref.id}",+ "name": name,+ "file": None,+ "plainText": None,+ "boolean": None,+ "reference": graphene.Node.to_global_id(attr.entity_type, ref.pk),+ }+ ],+ }+ for ref, attr, name in references+ ]+ for attr_data in attributes_data:+ assert attr_data in expected_attributes_data++def test_update_product_variant_change_attribute_values_ordering(staff_api_client,variant,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex bdc7c819c9..10421a2277 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -6217,6 +6217,7 @@ enum AttributeInputTypeEnum @doc(category: "Attributes") {MULTISELECTFILEREFERENCE+ SINGLE_REFERENCENUMERICRICH_TEXTPLAIN_TEXT@@ -21500,6 +21501,13 @@ input AttributeValueInput @doc(category: "Attributes") {"""File content type."""contentType: String+ """+ ID of the referenced entity for single reference attribute.++ Added in Saleor 3.22.+ """+ reference: ID+"""List of entity IDs that will be used as references."""references: [ID!]@@ -21805,6 +21813,13 @@ input BulkAttributeValueInput @doc(category: "Products") {"""File content type."""contentType: String+ """+ ID of the referenced entity for single reference attribute.++ Added in Saleor 3.22.+ """+ reference: ID+"""List of entity IDs that will be used as references."""references: [ID!]