Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Bulk create attribute value (#15494)
Iga Karbowiakcae629dc4166
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.pyindex 77044b5c2a..161a5f4662 100644--- a/saleor/attribute/models/base.py+++ b/saleor/attribute/models/base.py@@ -211,6 +211,133 @@ class AttributeTranslation(Translation):return {"name": self.name}+class AttributeValueManager(models.Manager):+ def _prepare_query_for_bulk_operation(self, objects_data):+ query_params = models.Q()++ for obj in objects_data:+ defaults = obj.pop("defaults")+ query_params |= models.Q(**obj)+ obj["defaults"] = defaults++ return self.filter(query_params)++ def _is_correct_record(self, record, obj):+ is_correct_record = (+ getattr(record, field_name) == field_value+ for field_name, field_value in obj.items()+ if field_name != "defaults"+ )+ return all(is_correct_record)++ def bulk_get_or_create(self, objects_data):+ # this method mimics django's queryset.get_or_create method on bulk objects+ # instead of performing it one by one+ # https://docs.djangoproject.com/en/5.0/ref/models/querysets/#get-or-create++ results = []+ objects_not_in_db: list[AttributeValue] = []++ # prepare a list that will save order index of attribute values+ objects_enumerated = list(enumerate(objects_data))+ query = self._prepare_query_for_bulk_operation(objects_data)++ # iterate over all records in db and check if they match any of objects data+ for record in query.iterator():+ # iterate over all objects data and check if they match any of records in db+ for index, obj in objects_enumerated:+ if self._is_correct_record(record, obj):+ # upon finding existing record add it to results+ results.append((index, record))+ # remove it from objects list, so it won't be added to new records+ objects_enumerated.remove((index, obj))++ break++ # add what is left to the list of new records+ self._add_new_records(objects_enumerated, objects_not_in_db, results)+ # sort results by index as db record order might be different from sort_order+ results.sort()+ results = [obj for index, obj in results]++ if objects_not_in_db:+ # After migrating to Django 4.0 we should use `update_conflicts` instead+ # of `ignore_conflicts`+ # https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-create+ self.bulk_create(+ objects_not_in_db, # type: ignore[arg-type]+ ignore_conflicts=True,+ )++ return results++ def bulk_update_or_create(self, objects_data):+ # this method mimics django's queryset.update_or_create method on bulk objects+ # https://docs.djangoproject.com/en/5.0/ref/models/querysets/#update-or-create+ results = []+ objects_not_in_db: list[AttributeValue] = []+ objects_to_be_updated = []+ update_fields = set()+ objects_enumerated = list(enumerate(objects_data))+ query = self._prepare_query_for_bulk_operation(objects_data)++ # iterate over all records in db and check if they match any of objects data+ for record in query.iterator():+ # iterate over all objects data and check if they match any of records in db+ for index, obj in objects_enumerated:+ if self._is_correct_record(record, obj):+ # upon finding a matching record, update it with defaults+ for key, value in obj["defaults"].items():+ setattr(record, key, value)+ update_fields.add(key)++ # add it to results and objects to be updated+ results.append((index, record))++ # add it to objects to be updated, so it can be bulk updated later+ objects_to_be_updated.append(record)++ # remove it from objects data, so it won't be added to new records+ objects_enumerated.remove((index, obj))++ break++ # add what is left to the list of new records+ self._add_new_records(objects_enumerated, objects_not_in_db, results)++ # sort results by index as db record order might be different from sort_order+ results.sort()+ results = [obj for index, obj in results]++ if objects_not_in_db:+ # After migrating to Django 4.0 we should use `update_conflicts` instead+ # of `ignore_conflicts`+ # https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-create+ self.bulk_create(+ objects_not_in_db, # type: ignore[arg-type]+ ignore_conflicts=True,+ )++ if objects_to_be_updated:+ self.bulk_update(+ objects_to_be_updated,+ fields=update_fields, # type: ignore[arg-type]+ )++ return results++ def _add_new_records(self, objects_enumerated, objects_not_in_db, results):+ for index, obj in objects_enumerated:+ # updating object data with defaults as they contain new values+ defaults = obj.pop("defaults")+ obj.update(defaults)++ # add new record to the list of new records, so it can be bulk created later+ record = self.model(**obj)+ objects_not_in_db.append(record)+ results.append((index, record))++class AttributeValue(ModelWithExternalReference):name = models.CharField(max_length=250)# keeps hex code color value in #RRGGBBAA format@@ -250,6 +377,8 @@ class AttributeValue(ModelWithExternalReference):)sort_order = models.IntegerField(editable=False, db_index=True, null=True)+ objects = AttributeValueManager()+class Meta:ordering = ("sort_order", "pk")unique_together = ("slug", "attribute")diff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.pyindex 17cd94aff9..a5fa50b8ac 100644--- a/saleor/attribute/utils.py+++ b/saleor/attribute/utils.py@@ -51,16 +51,27 @@ def associate_attribute_values_to_instance(def validate_attribute_owns_values(attr_val_map: dict[int, list]) -> None:- values = defaultdict(set)- for value in AttributeValue.objects.filter(+ values_map = defaultdict(set)+ slug_value_to_value_map = {}+ values = AttributeValue.objects.filter(attribute_id__in=attr_val_map.keys(),- pk__in=[v.pk for values in attr_val_map.values() for v in values],- ).iterator():- values[value.attribute_id].add(value.id)+ # slug is used as newly created values have no id yet because of+ # using `ignore_conflicts=True` flag in `bulk_create+ slug__in=[v.slug for values in attr_val_map.values() for v in values],+ )+ for value in values:+ values_map[value.attribute_id].add(value.slug)+ slug_value_to_value_map[value.slug] = value- for attribute_id, value_ids in attr_val_map.items():- if values[attribute_id] != {v.pk for v in value_ids}:+ for attribute_id, attr_values in attr_val_map.items():+ if values_map[attribute_id] != {v.slug for v in attr_values}:raise AssertionError("Some values are not from the provided attribute.")+ # Update the attr_val_map to use the created AttributeValue instances with+ # id set. This is needed as `ignore_conflicts=True` flag in `bulk_create+ # is used in `AttributeValueManager`+ attr_val_map[attribute_id] = [+ slug_value_to_value_map[v.slug] for v in attr_values+ ]def _associate_attribute_to_instance(diff --git a/saleor/graphql/attribute/enums.py b/saleor/graphql/attribute/enums.pyindex 190d9623f3..a3507e818b 100644--- a/saleor/graphql/attribute/enums.py+++ b/saleor/graphql/attribute/enums.py@@ -1,3 +1,5 @@+from enum import Enum+import graphenefrom ...attribute import AttributeEntityType, AttributeInputType, AttributeType@@ -19,3 +21,10 @@ AttributeEntityTypeEnum = graphene.Enum([(str_to_enum(name.upper()), code) for code, name in AttributeEntityType.CHOICES],)AttributeEntityTypeEnum.doc_category = DOC_CATEGORY_ATTRIBUTES+++class AttributeValueBulkActionEnum(Enum):+ NONE = None+ CREATE = "create"+ GET_OR_CREATE = "get_or_create"+ UPDATE_OR_CREATE = "update_or_create"diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex 956d54e90a..fd6cc9bf9e 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -4,6 +4,7 @@ from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom ....attribute import AttributeInputType+from ....attribute.models import AttributeValuefrom ....page.error_codes import PageErrorCodefrom ....product.error_codes import ProductErrorCodefrom ..utils import (@@ -2090,7 +2091,8 @@ def test_prepare_attribute_values(color_attribute):)# when- prepare_attribute_values(color_attribute, values.values)+ values_to_create = prepare_attribute_values(color_attribute, values.values)[1]+ AttributeValue.objects.bulk_create(values_to_create)# thencolor_attribute.refresh_from_db()@@ -2122,7 +2124,8 @@ def test_prepare_attribute_values_prefer_the_slug_match(color_attribute):)# when- result = prepare_attribute_values(color_attribute, values.values)+ result, values_to_create = prepare_attribute_values(color_attribute, values.values)+ AttributeValue.objects.bulk_create(values_to_create)# thencolor_attribute.refresh_from_db()@@ -2152,7 +2155,8 @@ def test_prepare_attribute_values_that_gives_the_same_slug(color_attribute):)# when- result = prepare_attribute_values(color_attribute, values.values)+ result, values_to_create = prepare_attribute_values(color_attribute, values.values)+ AttributeValue.objects.bulk_create(values_to_create)# thencolor_attribute.refresh_from_db()diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 47ffa896b2..ade2810d1b 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -9,7 +9,6 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import Qfrom django.db.models.expressions import Exists, OuterRef-from django.db.utils import IntegrityErrorfrom django.template.defaultfilters import truncatecharsfrom django.utils import timezonefrom django.utils.text import slugify@@ -18,9 +17,8 @@ from text_unidecode import unidecodefrom ...attribute import AttributeEntityType, AttributeInputTypefrom ...attribute import models as attribute_models-from ...attribute.utils import (- associate_attribute_values_to_instance,-)+from ...attribute.models import AttributeValue+from ...attribute.utils import associate_attribute_values_to_instancefrom ...core.utils import (generate_unique_slug,prepare_unique_attribute_value_slug,@@ -35,6 +33,7 @@ from ...product.error_codes import ProductErrorCodefrom ..core.utils import from_global_id_or_error, get_duplicated_valuesfrom ..core.validators import validate_one_of_args_is_in_mutationfrom ..utils import get_nodes+from .enums import AttributeValueBulkActionEnumif TYPE_CHECKING:from django.db.models import QuerySet@@ -194,22 +193,19 @@ class AttributeAssignmentMixin:@classmethoddef _create_value_instance(cls, attribute, attr_value, external_ref):- try:- value_slug = prepare_unique_attribute_value_slug(- attribute, slugify(unidecode(attr_value))- )- value = attribute_models.AttributeValue.objects.create(- external_reference=external_ref,- attribute=attribute,- name=attr_value,- slug=value_slug,- )- except IntegrityError:- raise ValidationError(- "Attribute value with given externalReference already exists."- )-- return value+ return (+ (+ AttributeValueBulkActionEnum.CREATE,+ AttributeValue(+ external_reference=external_ref,+ attribute=attribute,+ name=attr_value,+ slug=prepare_unique_attribute_value_slug(+ attribute, slugify(unidecode(attr_value))+ ),+ ),+ ),+ )@classmethoddef clean_input(@@ -386,7 +382,7 @@ class AttributeAssignmentMixin:def save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):"""Save the cleaned input into the database against the given instance.- Note: this should always be ran inside a transaction.+ Note: this should always be run inside a transaction.:param instance: the product or variant to associate the attribute against.:param cleaned_input: the cleaned user input (refer to clean_attributes)@@ -405,6 +401,9 @@ class AttributeAssignmentMixin:AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,}clean_assignment = []+ pre_save_bulk = defaultdict(+ lambda: defaultdict(list) # type: ignore[var-annotated]+ )attr_val_map = defaultdict(list)for attribute, attr_values in cleaned_input:@@ -424,9 +423,23 @@ class AttributeAssignmentMixin:attribute_values = pre_save_func(instance, attribute, attr_values)if not attribute_values:+ # to ensure that attribute will be present in variable `pre_save_bulk`,+ # so function `associate_attribute_values_to_instance` will be called+ # properly for all attributes, even in case when attribute has no values+ pre_save_bulk[AttributeValueBulkActionEnum.NONE].setdefault(+ attribute, []+ )+ else:+ for key, value in attribute_values:+ pre_save_bulk[key][attribute].append(value)++ attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)++ for attribute, values in attribute_and_values.items():+ if not values:clean_assignment.append(attribute.pk)else:- attr_val_map[attribute.pk].extend(attribute_values)+ attr_val_map[attribute.pk].extend(values)associate_attribute_values_to_instance(instance, attr_val_map)@@ -450,8 +463,7 @@ class AttributeAssignmentMixin:external_ref = attr_values.dropdown.external_referenceif external_ref and attr_value:- value = cls._create_value_instance(attribute, attr_value, external_ref)- return (value,)+ return cls._create_value_instance(attribute, attr_value, external_ref)if external_ref:value = attribute_models.AttributeValue.objects.get(@@ -461,17 +473,17 @@ class AttributeAssignmentMixin:raise ValidationError("Attribute value with given externalReference can't be found")- return (value,)+ return ((AttributeValueBulkActionEnum.NONE, value),)if id := attr_values.dropdown.id:_, attr_value_id = from_global_id_or_error(id)value = attribute_models.AttributeValue.objects.get(pk=attr_value_id)if not value:raise ValidationError("Attribute value with given ID can't be found")- return (value,)+ return ((AttributeValueBulkActionEnum.NONE, value),)if attr_value:- return prepare_attribute_values(attribute, [attr_value])+ return cls._prepare_attribute_values(attribute, [attr_value])return tuple()@@ -490,28 +502,39 @@ class AttributeAssignmentMixin:if external_ref and attr_value:value = cls._create_value_instance(attribute, attr_value, external_ref)- return (value,)+ return valueif external_ref:- value = attribute_models.AttributeValue.objects.get(+ value = attribute_models.AttributeValue.objects.filter(external_reference=external_ref- )+ ).first()if not value:raise ValidationError("Attribute value with given externalReference can't be found")- return (value,)+ return (+ (+ AttributeValueBulkActionEnum.NONE,+ value,+ ),+ )if id := attr_values.swatch.id:_, attr_value_id = from_global_id_or_error(id)- model = attribute_models.AttributeValue.objects.get(pk=attr_value_id)- if not model:+ value = attribute_models.AttributeValue.objects.filter(+ pk=attr_value_id+ ).first()+ if not value:raise ValidationError("Attribute value with given ID can't be found")- return (model,)+ return (+ (+ AttributeValueBulkActionEnum.NONE,+ value,+ ),+ )if attr_value := attr_values.swatch.value:- model = prepare_attribute_values(attribute, [attr_value])- return model+ return cls._prepare_attribute_values(attribute, [attr_value])return tuple()@@ -530,10 +553,9 @@ class AttributeAssignmentMixin:external_ref = attr_value.external_referenceif external_ref and attr_value.value:- value = cls._create_value_instance(+ return cls._create_value_instance(attribute, attr_value.value, external_ref)- return (value,)if external_ref:value = attribute_models.AttributeValue.objects.get(@@ -543,7 +565,7 @@ class AttributeAssignmentMixin:raise ValidationError("Attribute value with given externalReference can't be found")- return (value,)+ return valueif attr_value.id:_, attr_value_id = from_global_id_or_error(attr_value.id)@@ -560,11 +582,14 @@ class AttributeAssignmentMixin:if attr_value.value:attr_value_model = prepare_attribute_values(attribute, [attr_value.value]- )[0]+ )[0][0]+ attr_value_model.save()if attr_value_model.id not in [a.id for a in attribute_values]:attribute_values.append(attr_value_model)- return attribute_values+ return [+ (AttributeValueBulkActionEnum.NONE, value) for value in attribute_values+ ]@classmethoddef _pre_save_numeric_values(@@ -597,9 +622,7 @@ class AttributeAssignmentMixin:if not attr_values.values:return tuple()- result = prepare_attribute_values(attribute, attr_values.values)-- return tuple(result)+ return cls._prepare_attribute_values(attribute, attr_values.values)@classmethoddef _pre_save_rich_text_values(@@ -636,7 +659,7 @@ class AttributeAssignmentMixin:@classmethoddef _pre_save_boolean_values(cls,- instance: T_INSTANCE,+ _instance: T_INSTANCE,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,):@@ -644,15 +667,15 @@ class AttributeAssignmentMixin:return tuple()boolean = bool(attr_values.boolean)- value, _ = attribute.values.get_or_create(- attribute=attribute,- slug=slugify(unidecode(f"{attribute.id}_{boolean}")),- defaults={+ value = {+ "attribute": attribute,+ "slug": slugify(unidecode(f"{attribute.id}_{boolean}")),+ "defaults": {"name": f"{attribute.name}: {'Yes' if boolean else 'No'}","boolean": boolean,},- )- return (value,)+ }+ return ((AttributeValueBulkActionEnum.GET_OR_CREATE, value),)@classmethoddef _pre_save_date_time_values(@@ -690,14 +713,13 @@ class AttributeAssignmentMixin:attribute: attribute_models.Attribute,value_defaults: dict,):- update_or_create = attribute.values.update_or_createslug = slugify(unidecode(f"{instance.id}_{attribute.id}"))- value, _created = update_or_create(- attribute=attribute,- slug=slug,- defaults=value_defaults,- )- return (value,)+ value = {+ "attribute": attribute,+ "slug": slug,+ "defaults": value_defaults,+ }+ return ((AttributeValueBulkActionEnum.UPDATE_OR_CREATE, value),)@classmethoddef _pre_save_reference_values(@@ -715,7 +737,6 @@ class AttributeAssignmentMixin:entity_data = cls.ENTITY_TYPE_MAPPING[attribute.entity_type]field_name = entity_data.name_field- get_or_create = attribute.values.get_or_createreference_list = []attr_value_field = entity_data.value_field@@ -723,15 +744,22 @@ class AttributeAssignmentMixin:name = getattr(ref, field_name)if attribute.entity_type == AttributeEntityType.PRODUCT_VARIANT:name = f"{ref.product.name}: {name}" # type: ignore+reference_list.append(- get_or_create(- attribute=attribute,- slug=slugify(unidecode(f"{instance.id}_{ref.id}")), # type: ignore- defaults={"name": name},- **{attr_value_field: ref},- )[0]+ (+ AttributeValueBulkActionEnum.GET_OR_CREATE,+ {+ "attribute": attribute,+ "slug": slugify(+ unidecode(f"{instance.id}_{ref.id}") # type: ignore+ ),+ "defaults": {"name": name},+ attr_value_field: ref,+ },+ ))- return tuple(reference_list)++ return reference_list@classmethoddef _pre_save_file_value(@@ -754,15 +782,47 @@ class AttributeAssignmentMixin:instance, attribute, "file_url", attr_value.file_url)if value is None:- value = attribute_models.AttributeValue(+ value = AttributeValue(attribute=attribute,file_url=file_url,name=name,content_type=attr_value.content_type,)value.slug = generate_unique_slug(value, name)- value.save()- return (value,)+ return ((AttributeValueBulkActionEnum.CREATE, value),)+ return ((None, value),)++ @classmethod+ def _prepare_attribute_values(cls, attribute, values):+ results, values_to_create = prepare_attribute_values(attribute, values)+ return [+ (AttributeValueBulkActionEnum.NONE, record)+ for record in results+ if record not in values_to_create+ ] + [+ (AttributeValueBulkActionEnum.CREATE, record) for record in values_to_create+ ]++ @classmethod+ def _bulk_create_pre_save_values(cls, pre_save_bulk):+ results: dict["Attribute", list[AttributeValue]] = defaultdict(list)++ for action, attribute_data in pre_save_bulk.items():+ for attribute, values in attribute_data.items():+ if action == AttributeValueBulkActionEnum.CREATE:+ values = AttributeValue.objects.bulk_create(values)+ elif action == AttributeValueBulkActionEnum.UPDATE_OR_CREATE:+ values = AttributeValue.objects.bulk_update_or_create(values)+ elif action == AttributeValueBulkActionEnum.GET_OR_CREATE:+ values = AttributeValue.objects.bulk_get_or_create(values)+ else:+ # ensuring that empty values will be added to results,+ # so assignments will be removed properly in that case+ results.setdefault(attribute, [])++ results[attribute].extend(values)++ return resultsclass PageAttributeAssignmentMixin(AttributeAssignmentMixin):@@ -816,6 +876,9 @@ class PageAttributeAssignmentMixin(AttributeAssignmentMixin):}clean_assignment = []+ pre_save_bulk = defaultdict(+ lambda: defaultdict(list) # type: ignore[var-annotated]+ )attr_val_map = defaultdict(list)for attribute, attr_values in cleaned_input:@@ -835,11 +898,26 @@ class PageAttributeAssignmentMixin(AttributeAssignmentMixin):attribute_values = pre_save_func(instance, attribute, attr_values)if not attribute_values:+ # to ensure that attribute will be present in variable `pre_save_bulk`,+ # so function `associate_attribute_values_to_instance` will be called+ # properly for all attributes, even in case when attribute has no values+ pre_save_bulk[AttributeValueBulkActionEnum.NONE].setdefault(+ attribute, []+ )+ else:+ for key, value in attribute_values:+ pre_save_bulk[key][attribute].append(value)++ attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)++ for attribute, values in attribute_and_values.items():+ if not values:clean_assignment.append(attribute.pk)else:- attr_val_map[attribute.pk].extend(attribute_values)+ attr_val_map[attribute.pk].extend(values)associate_attribute_values_to_instance(instance, attr_val_map)+if clean_assignment:values = attribute_models.AttributeValue.objects.filter(attribute_id__in=clean_assignment@@ -900,8 +978,10 @@ class ProductAttributeAssignmentMixin(AttributeAssignmentMixin):}clean_assignment = []+ pre_save_bulk = defaultdict(+ lambda: defaultdict(list) # type: ignore[var-annotated]+ )attr_val_map = defaultdict(list)-for attribute, attr_values in cleaned_input:is_handled_by_values_field = (attr_values.values@@ -919,11 +999,26 @@ class ProductAttributeAssignmentMixin(AttributeAssignmentMixin):attribute_values = pre_save_func(instance, attribute, attr_values)if not attribute_values:+ # to ensure that attribute will be present in variable `pre_save_bulk`,+ # so function `associate_attribute_values_to_instance` will be called+ # properly for all attributes, even in case when attribute has no values+ pre_save_bulk[AttributeValueBulkActionEnum.NONE].setdefault(+ attribute, []+ )+ else:+ for key, value in attribute_values:+ pre_save_bulk[key][attribute].append(value)++ attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)++ for attribute, values in attribute_and_values.items():+ if not values:clean_assignment.append(attribute.pk)else:- attr_val_map[attribute.pk].extend(attribute_values)+ attr_val_map[attribute.pk].extend(values)associate_attribute_values_to_instance(instance, attr_val_map)+if clean_assignment:values = attribute_models.AttributeValue.objects.filter(attribute_id__in=clean_assignment@@ -966,8 +1061,7 @@ def prepare_attribute_values(attribute: attribute_models.Attribute, values: list# extend name to slug value to not create two elements with the same namename_to_value_map[instance.name] = instance- attribute_models.AttributeValue.objects.bulk_create(values_to_create)- return result+ return result, values_to_createdef get_existing_slugs(attribute: attribute_models.Attribute, values: list[str]):diff --git a/saleor/graphql/product/tests/benchmark/test_product_bulk_create.py b/saleor/graphql/product/tests/benchmark/test_product_bulk_create.pynew file mode 100644index 0000000000..fbfc8d1697--- /dev/null+++ b/saleor/graphql/product/tests/benchmark/test_product_bulk_create.py@@ -0,0 +1,167 @@+import json++import graphene+import pytest++from .....attribute.models import Attribute+from .....product.models import Product+from ....tests.utils import get_graphql_content++PRODUCT_BULK_CREATE_MUTATION = """+ mutation ProductBulkCreate(+ $products: [ProductBulkCreateInput!]!+ ) {+ productBulkCreate(products: $products) {+ results {+ errors {+ path+ code+ message+ warehouses+ channels+ }+ product{+ id+ name+ slug+ media{+ url+ alt+ type+ oembedData+ }+ category{+ name+ }+ description+ attributes{+ attribute{+ slug+ }+ values{+ value+ }+ }+ channelListings{+ id+ channel{+ name+ }+ }+ variants{+ name+ stocks{+ warehouse{+ slug+ }+ quantity+ }+ }+ }+ }+ count+ }+ }+"""+++def attributes_without_values():+ return Attribute.objects.bulk_create(+ [Attribute(slug=f"attribute-{x}", name=f"Attribute {x}") for x in range(1000)]+ )++[email protected]_queries(autouse=False)+def test_product_bulk_create_with_base_data(+ staff_api_client,+ product_type,+ category,+ description_json,+ permission_manage_products,+ color_attribute,+ date_attribute,+ attribute_without_values,+ attributes_without_values,+):+ # given+ description_json_string = 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"++ product_type.product_attributes.add(date_attribute)+ product_type.product_attributes.add(attribute_without_values)+ product_type.product_attributes.add(*attributes_without_values)++ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_1,+ "description": description_json_string,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),+ "values": [+ "#000000",+ ],+ },+ {+ "id": graphene.Node.to_global_id("Attribute", date_attribute.pk),+ "values": ["2021-06-01"],+ },+ ]+ + [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", attribute_without_values.pk+ ),+ "values": ["test value"],+ }+ ],+ "weight": 2,+ },+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_2,+ "slug": f"{base_product_slug}-2",+ "description": description_json_string,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),+ "values": [f"{attribute_without_values.pk}-value"],+ }+ for attribute in attributes_without_values+ ],+ },+ ]++ assert Product.objects.count() == 0++ # 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+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2++ assert Product.objects.count() == 2