Skip to content

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

Implement attribute input types for attributes (#4255)

NyanKiyoshi541740cbebd7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c5dfd3a688..66ab4844e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Attributes can now be associated to multiple product types. - #4266 by @NyanKiyoshi
- The `Attribute` model's `product_type` field was renamed to `product_types` (M2M related manager). - #4266 by @NyanKiyoshi
- Added `attributeAssign(...)` and `attributeUnassign(...)` mutations in the GraphQL API. - #4266 by @NyanKiyoshi
+- Implemented a `input_type` field into the attribute models and refactored the product attributes to be able to store more than one value per attribute per product. - #4255 by @NyanKiyoshi.
## [Unreleased]
diff --git a/saleor/core/fields.py b/saleor/core/fields.py
index 07b3d1f358..728234534c 100644
--- a/saleor/core/fields.py
+++ b/saleor/core/fields.py
@@ -1,7 +1,9 @@
import json
from typing import Callable
-from django.contrib.postgres.fields.jsonb import JSONField
+from django.contrib.postgres.fields import jsonb
+from django.contrib.postgres.fields.jsonb import JSONField, KeyTransform
+from django.db.models import Transform
from django.utils.translation import gettext_lazy
@@ -23,3 +25,58 @@ class SanitizedJSONField(JSONField):
def get_db_prep_save(self, value: dict, connection):
"""Sanitize the value for saving using the passed sanitizer."""
return json.dumps(self._sanitizer_method(value))
+
+
+class FilterableJSONBField(jsonb.JSONField):
+ """This only redefine the JSONB field of django to register a custom lookup key
+ that allow us to filter JSONB field by key value no matter what. Where django's
+ behavior is to filter by key index position if the lookup value is a string number.
+
+ This is a temporary fix waiting for a fix from django.
+
+ Refer to https://code.djangoproject.com/ticket/30566."""
+
+ _FROM_KEY_LOOKUP = "from_key_"
+ _FROM_KEY_LOOKUP_LEN = len(_FROM_KEY_LOOKUP)
+
+ def get_transform(self, lookup_name):
+ if not lookup_name.startswith(self._FROM_KEY_LOOKUP):
+ return super().get_lookup(lookup_name)
+ lookup_name = lookup_name[self._FROM_KEY_LOOKUP_LEN :] # noqa: black conflict
+ return KeyTransformFactory(lookup_name)
+
+
+class FromKeyLookup(Transform):
+ operator = "->"
+ nested_operator = "#>"
+
+ def __init__(self, key_name, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.key_name = key_name
+
+ def as_sql(self, compiler, connection):
+ key_transforms = [self.key_name]
+ previous = self.lhs
+
+ while isinstance(previous, KeyTransform):
+ key_transforms.insert(0, previous.key_name)
+ previous = previous.lhs
+
+ lhs, params = compiler.compile(previous)
+
+ if len(key_transforms) > 1:
+ return (
+ "(%s %s %%s)" % (lhs, self.nested_operator),
+ [key_transforms] + params,
+ )
+
+ lookup = "'%s'" % self.key_name
+ return "(%s %s %s)" % (lhs, self.operator, lookup), params
+
+
+class KeyTransformFactory:
+ def __init__(self, key_name):
+ self.key_name = key_name
+
+ def __call__(self, *args, **kwargs):
+ return FromKeyLookup(self.key_name, *args, **kwargs)
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index 3834c81be7..ac294e7872 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -218,7 +218,7 @@ class AttributesMixin:
attribute_id=attr.pk, name=value, slug=slugify(value)
)
value.save()
- attributes[smart_text(attr.pk)] = smart_text(value.pk)
+ attributes[smart_text(attr.pk)] = [smart_text(value.pk)]
return attributes
@@ -484,7 +484,7 @@ class VariantImagesSelectForm(forms.Form):
class AttributeForm(forms.ModelForm):
class Meta:
model = Attribute
- exclude = []
+ exclude = ["input_type"]
labels = {
"name": pgettext_lazy("Product display name", "Display name"),
"slug": pgettext_lazy("Product internal name", "Internal name"),
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 11f59c3502..b5f06d09ee 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -153,11 +153,7 @@ def product_create(request, type_pk):
@permission_required("product.manage_products")
def product_edit(request, pk):
product = get_object_or_404(Product.objects.prefetch_related("variants"), pk=pk)
- for k, v in product.attributes.items():
- product.attributes[k] = [v]
- product.save()
form = forms.ProductForm(request.POST or None, instance=product)
-
edit_variant = not product.product_type.has_variants
if edit_variant:
variant = product.variants.first()
diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.py
index 381db05404..14c7d611be 100644
--- a/saleor/data_feeds/google_merchant.py
+++ b/saleor/data_feeds/google_merchant.py
@@ -113,8 +113,8 @@ def item_brand(item: ProductVariant, attributes_dict, attribute_values_dict):
if brand is None:
brand = item.product.attributes.get(str(publisher_attribute_pk))
- if brand is not None:
- brand_name = attribute_values_dict.get(brand)
+ if brand:
+ brand_name = attribute_values_dict.get(brand[0])
if brand_name is not None:
return brand_name
return brand
diff --git a/saleor/graphql/product/descriptions.py b/saleor/graphql/product/descriptions.py
index 1e14129a28..cafb077aca 100644
--- a/saleor/graphql/product/descriptions.py
+++ b/saleor/graphql/product/descriptions.py
@@ -1,4 +1,5 @@
class AttributeDescriptions:
+ INPUT_TYPE = "The input type to use for entering attribute values in the dashboard."
NAME = "Name of an attribute displayed in the interface."
SLUG = "Internal representation of an attribute name."
VALUES = "List of attribute's values."
diff --git a/saleor/graphql/product/enums.py b/saleor/graphql/product/enums.py
index fbcc0e4383..bd95a72eab 100644
--- a/saleor/graphql/product/enums.py
+++ b/saleor/graphql/product/enums.py
@@ -1,5 +1,10 @@
import graphene
+from ...product import AttributeInputType
+from ..core.enums import to_enum
+
+AttributeInputTypeEnum = to_enum(AttributeInputType)
+
class AttributeTypeEnum(graphene.Enum):
PRODUCT = "PRODUCT"
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 0a337af7e3..75ccde6b58 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -43,8 +43,8 @@ def filter_products_by_attributes(qs, filter_value):
functools.reduce(
operator.or_,
[
- Q(**{"variants__attributes__%s" % (key,): v})
- | Q(**{"attributes__%s" % (key,): v})
+ Q(**{f"variants__attributes__from_key_{key}__has_key": str(v)})
+ | Q(**{f"attributes__from_key_{key}__has_key": str(v)})
for v in values
],
)
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 4edf83c606..59c591d2a8 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -5,7 +5,7 @@ from django.core.exceptions import ValidationError
from django.db.models import Q
from django.template.defaultfilters import slugify
-from ....product import models
+from ....product import AttributeInputType, models
from ...core.mutations import (
BaseMutation,
ClearMetaBaseMutation,
@@ -14,9 +14,9 @@ from ...core.mutations import (
UpdateMetaBaseMutation,
)
from ...core.utils import from_global_id_strict_type
-from ...product.enums import AttributeTypeEnum
from ...product.types import ProductType
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
+from ..enums import AttributeInputTypeEnum, AttributeTypeEnum
from ..types import Attribute
@@ -26,6 +26,7 @@ class AttributeValueCreateInput(graphene.InputObjectType):
class AttributeCreateInput(graphene.InputObjectType):
+ input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)
name = graphene.String(required=True, description=AttributeDescriptions.NAME)
slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)
values = graphene.List(
@@ -287,6 +288,23 @@ class AttributeAssign(BaseAttributeAssignmentMutation):
}
)
+ # check if attributes' input type is assignable to variants
+ is_not_assignable_to_variant = models.Attribute.objects.filter(
+ Q(pk__in=variant_attrs_pks)
+ & Q(input_type__in=AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS)
+ ).exists()
+
+ if is_not_assignable_to_variant:
+ raise ValidationError(
+ {
+ "operations": (
+ f"Attributes having for input types "
+ f"{AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS} "
+ f"cannot be assigned as variant attributes"
+ )
+ }
+ )
+
@classmethod
def save_field_values(cls, product_type, field, pks):
"""Add in bulk the PKs to assign to a given product type."""
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 3c162bb068..e81ecc97d4 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -37,7 +37,7 @@ from ..types import (
ProductImage,
ProductVariant,
)
-from ..utils import attributes_to_hstore
+from ..utils import attributes_to_json
class CategoryInput(graphene.InputObjectType):
@@ -394,7 +394,9 @@ class CategoryClearPrivateMeta(ClearMetaBaseMutation):
class AttributeValueInput(InputObjectType):
slug = graphene.String(required=True, description="Slug of an attribute.")
- value = graphene.String(required=True, description="Value of an attribute.")
+ values = graphene.List(
+ graphene.String, required=True, description="Value of an attribute."
+ )
class ProductInput(graphene.InputObjectType):
@@ -496,7 +498,7 @@ class ProductCreate(ModelMutation):
if attributes and product_type:
qs = product_type.product_attributes.prefetch_related("values")
try:
- attributes = attributes_to_hstore(attributes, qs)
+ attributes = attributes_to_json(attributes, qs)
except ValueError as e:
raise ValidationError({"attributes": str(e)})
else:
@@ -677,7 +679,7 @@ class ProductVariantCreate(ModelMutation):
@classmethod
def clean_product_type_attributes(cls, attributes_qs, attributes_input):
# transform attributes_input list to a dict of slug:value pairs
- attributes_input = {item["slug"]: item["value"] for item in attributes_input}
+ attributes_input = {item["slug"]: item["values"] for item in attributes_input}
for attr in attributes_qs:
value = attributes_input.get(attr.slug, None)
@@ -701,7 +703,7 @@ class ProductVariantCreate(ModelMutation):
variant_attrs = product_type.variant_attributes.prefetch_related("values")
try:
cls.clean_product_type_attributes(variant_attrs, attributes_input)
- attributes = attributes_to_hstore(attributes_input, variant_attrs)
+ attributes = attributes_to_json(attributes_input, variant_attrs)
except ValueError as e:
raise ValidationError({"attributes": str(e)})
else:
diff --git a/saleor/graphql/product/types/attributes.py b/saleor/graphql/product/types/attributes.py
index 3f18a0fbd0..f792bee470 100644
--- a/saleor/graphql/product/types/attributes.py
+++ b/saleor/graphql/product/types/attributes.py
@@ -13,7 +13,7 @@ from ...translations.enums import LanguageCodeEnum
from ...translations.resolvers import resolve_translation
from ...translations.types import AttributeTranslation, AttributeValueTranslation
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
-from ..enums import AttributeValueType
+from ..enums import AttributeInputTypeEnum, AttributeValueType
COLOR_PATTERN = r"^(#[0-9a-fA-F]{3}|#(?:[0-9a-fA-F]{2}){2,4}|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))$" # noqa
color_pattern = re.compile(COLOR_PATTERN)
@@ -47,6 +47,11 @@ class AttributeValue(CountableDjangoObjectType):
resolver=resolve_translation,
)
+ input_type = gql_optimizer.field(
+ AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE),
+ model_field="attribute",
+ )
+
class Meta:
description = "Represents a value of an attribute."
only_fields = ["id", "sort_order"]
@@ -57,14 +62,23 @@ class AttributeValue(CountableDjangoObjectType):
def resolve_type(root: models.AttributeValue, *_args):
return resolve_attribute_value_type(root.value)
+ @staticmethod
+ @permission_required("product.manage_products")
+ def resolve_input_type(root: models.AttributeValue, *_args):
+ return root.input_type
+
class Attribute(CountableDjangoObjectType, MetadataObjectType):
+ input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)
+
name = graphene.String(description=AttributeDescriptions.NAME)
slug = graphene.String(description=AttributeDescriptions.SLUG)
+
values = gql_optimizer.field(
graphene.List(AttributeValue, description=AttributeDescriptions.VALUES),
model_field="values",
)
+
translation = graphene.Field(
AttributeTranslation,
language_code=graphene.Argument(
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 2f77c57374..1d7a537a27 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -70,7 +70,7 @@ def prefetch_products_collection_sorted(info, *_args, **_kwargs):
)
-def resolve_attribute_list(attributes_hstore, attributes_qs):
+def resolve_attribute_list(attributes_json, attributes_qs):
"""Resolve attributes dict into a list of `SelectedAttribute`s.
keys = list(attributes.keys())
@@ -87,11 +87,15 @@ def resolve_attribute_list(attributes_hstore, attributes_qs):
values_map[val.pk] = val
attributes_list = []
- for k, v in attributes_hstore.items():
+ for k, values in attributes_json.items():
attribute = attributes_map.get(int(k))
- value = values_map.get(int(v))
- if attribute and value:
- attributes_list.append(SelectedAttribute(attribute=attribute, value=value))
+
+ for v_pk in values:
+ value = values_map.get(int(v_pk))
+ if attribute and value:
+ attributes_list.append(
+ SelectedAttribute(attribute=attribute, value=value)
+ )
return attributes_list
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index 867d8e2d29..0b394aca64 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -1,45 +1,54 @@
+from collections import defaultdict
+from typing import List
+
from django.utils.text import slugify
-from ...product.models import Attribute
+from ...product import AttributeInputType, models
+
+
+def validate_attribute_input(instance: models.Attribute, values: List[str]):
+ if instance.input_type != AttributeInputType.MULTISELECT and len(values) != 1:
+ raise ValueError(f"A {instance.input_type} attribute must take only one value")
-def attributes_to_hstore(attribute_value_input, attributes_queryset):
+def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):
"""Transform attributes to the HStore representation.
Attributes configuration per product is stored in a HStore field as
a dict of IDs. This function transforms the list of `AttributeValueInput`
objects to this format.
"""
- attributes_map = {attr.slug: attr.id for attr in attributes_queryset}
-
- attributes_hstore = {}
+ attributes_map = {attr.slug: attr for attr in attributes_queryset}
+ attributes_json = defaultdict(list)
values_map = {}
for attr in attributes_queryset:
for value in attr.values.all():
values_map[value.slug] = value.id
- for attribute in attribute_value_input:
- attr_slug = attribute.get("slug")
+ for attribute_input in attribute_value_input:
+ attr_slug = attribute_input.get("slug")
if attr_slug not in attributes_map:
raise ValueError(
"Attribute %r doesn't belong to given product type." % (attr_slug,)
)
- value = attribute.get("value")
- if not value:
+ values = attribute_input.get("values")
+ if not values:
continue
- attribute_id = attributes_map[attr_slug]
- value_id = values_map.get(value)
+ attribute = attributes_map[attr_slug] # type: models.Attribute
+ validate_attribute_input(attribute, values)
+
+ for value in values:
+ value_id = values_map.get(value)
- if value_id is None:
- # `value_id` was not found; create a new AttributeValue
- # instance from the provided `value`.
- attr_instance = Attribute.objects.get(slug=attr_slug)
- obj = attr_instance.values.get_or_create(name=value, slug=slugify(value))[0]
- value_id = obj.pk
+ if value_id is None:
+ # `value_id` was not found; create a new AttributeValue
+ # instance from the provided `value`.
+ obj = attribute.values.get_or_create(name=value, slug=slugify(value))[0]
+ value_id = obj.pk
- attributes_hstore[str(attribute_id)] = str(value_id)
+ attributes_json[str(attribute.pk)].append(str(value_id))
- return attributes_hstore
+ return attributes_json
diff --git a/saleor/product/__init__.py b/saleor/product/__init__.py
index 369925b0c8..795ae05a8c 100644
--- a/saleor/product/__init__.py
+++ b/saleor/product/__init__.py
@@ -39,3 +39,18 @@ class VariantAvailabilityStatus:
return pgettext_lazy("Variant status", "out of stock")
else:
raise NotImplementedError("Unknown status: %s" % status)
+
+
+class AttributeInputType:
+ """The type that we expect to render the attribute's values as."""
+
+ DROPDOWN = "dropdown"
+ MULTISELECT = "multiselect"
+
+ CHOICES = [
+ (DROPDOWN, pgettext_lazy("Attribute input type", "Dropdown")),
+ (MULTISELECT, pgettext_lazy("Attribute input type", "Multi Select")),
+ ]
+
+ # list the input types that cannot be assigned to a variant
+ NON_ASSIGNABLE_TO_VARIANTS = [MULTISELECT]
diff --git a/saleor/product/filters.py b/saleor/product/filters.py
index 6a4fe3a535..05c3ffc77f 100644
--- a/saleor/product/filters.py
+++ b/saleor/product/filters.py
@@ -17,6 +17,15 @@ SORT_BY_FIELDS = OrderedDict(
)
+class JSONBArrayFilter(MultipleChoiceFilter):
+ def get_filter_predicate(self, v):
+ operator = f"{self.field_name}__has_key"
+ try:
+ return {operator: getattr(v, self.field.to_field_name)}
+ except (AttributeError, TypeError):
+ return {operator: v}
+
+
class ProductFilter(SortedFilterSet):
sort_by = OrderingFilter(
label=pgettext_lazy("Product list sorting form", "Sort by"),
@@ -62,8 +71,8 @@ class ProductFilter(SortedFilterSet):
def _get_product_attributes_filters(self):
filters = {}
for attribute in self.product_attributes:
- filters[attribute.slug] = MultipleChoiceFilter(
- field_name="attributes__%s" % attribute.pk,
+ filters[attribute.slug] = JSONBArrayFilter(
+ field_name=f"attributes__from_key_{attribute.pk}",
label=attribute.translated.name,
widget=CheckboxSelectMultiple,
choices=self._get_attribute_choices(attribute),
@@ -73,8 +82,8 @@ class ProductFilter(SortedFilterSet):
def _get_product_variants_attributes_filters(self):
filters = {}
for attribute in self.variant_attributes:
- filters[attribute.slug] = MultipleChoiceFilter(
- field_name="variants__attributes__%s" % attribute.pk,
+ filters[attribute.slug] = JSONBArrayFilter(
+ field_name=f"variants__attributes__from_key_{attribute.pk}",
label=attribute.translated.name,
widget=CheckboxSelectMultiple,
choices=self._get_attribute_choices(attribute),
diff --git a/saleor/product/migrations/0095_migrate_attrs_to_m2m.py b/saleor/product/migrations/0096_migrate_attrs_to_m2m.py
similarity index 98%
rename from saleor/product/migrations/0095_migrate_attrs_to_m2m.py
rename to saleor/product/migrations/0096_migrate_attrs_to_m2m.py
index b977c4778f..f779e6eb69 100644
--- a/saleor/product/migrations/0095_migrate_attrs_to_m2m.py
+++ b/saleor/product/migrations/0096_migrate_attrs_to_m2m.py
@@ -21,7 +21,7 @@ def migrate_fk_to_m2m(product_type_related_field):
class Migration(migrations.Migration):
- dependencies = [("product", "0094_auto_20190611_0952")]
+ dependencies = [("product", "0095_auto_20190618_0842")]
operations = [
# Rename the foreign keys to backup them before overriding and processing them
diff --git a/saleor/product/migrations/0097_attribute_input_type_multiple_values.py b/saleor/product/migrations/0097_attribute_input_type_multiple_values.py
new file mode 100644
index 0000000000..4f5b48033b
--- /dev/null
+++ b/saleor/product/migrations/0097_attribute_input_type_multiple_values.py
@@ -0,0 +1,58 @@
+# Generated by Django 2.2.2 on 2019-06-10 10:25
+
+from django.db import migrations, models
+
+from saleor.core.fields import FilterableJSONBField
+from saleor.product.models import validate_attribute_json
+
+
+def migrate_attributes_to_list(model_name):
+ def make_migration(apps, schema):
+ Model = apps.get_model("product", model_name)
+
+ for instance in Model.objects.all():
+ new_attributes = {}
+
+ for k, v in instance.attributes.items():
+ if not isinstance(v, list):
+ new_attributes[k] = [v]
+ else:
+ new_attributes[k] = v
+
+ instance.attributes = new_attributes
+ instance.save(update_fields=["attributes"])
+
+ return make_migration
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("product", "0096_migrate_attrs_to_m2m")]
+
+ operations = [
+ migrations.AddField(
+ model_name="attribute",
+ name="input_type",
+ field=models.CharField(
+ choices=[("dropdown", "Dropdown"), ("multiselect", "Multi Select")],
+ default="dropdown",
+ max_length=50,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="product",
+ name="attributes",
+ field=FilterableJSONBField(
+ blank=True, default=dict, validators=[validate_attribute_json]
+ ),
+ ),
+ migrations.AlterField(
+ model_name="productvariant",
+ name="attributes",
+ field=FilterableJSONBField(
+ blank=True, default=dict, validators=[validate_attribute_json]
+ ),
+ ),
+ migrations.RunPython(migrate_attributes_to_list("Product")),
+ migrations.RunPython(migrate_attributes_to_list("ProductVariant")),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 8b219b852e..84cf586a9f 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -3,7 +3,8 @@ from typing import Iterable
from uuid import uuid4
from django.conf import settings
-from django.contrib.postgres.fields import HStoreField, JSONField
+from django.contrib.postgres.fields import JSONField
+from django.core import exceptions
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import F, Q
@@ -24,7 +25,7 @@ from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
from ..core.exceptions import InsufficientStock
-from ..core.fields import SanitizedJSONField
+from ..core.fields import FilterableJSONBField, SanitizedJSONField
from ..core.models import (
ModelWithMetadata,
PublishableModel,
@@ -38,6 +39,29 @@ from ..core.weight import WeightUnits, zero_weight
from ..discount import DiscountInfo
from ..discount.utils import calculate_discounted_price
from ..seo.models import SeoModel, SeoModelTranslation
+from . import AttributeInputType
+
+
+def validate_attribute_json(value):
+ for k, values in value.items():
+ if not isinstance(k, str):
+ raise exceptions.ValidationError(
+ f"The key {k!r} should be of type str (got {type(k)})",
+ params={"k": k, "values": values},
+ )
+ if not isinstance(values, list):
+ raise exceptions.ValidationError(
+ f"The values of {k!r} should be of type list (got {type(values)})",
+ params={"k": k, "values": values},
+ )
+
+ for value_pk in values:
+ if not isinstance(value_pk, str):
+ raise exceptions.ValidationError(
+ f"The values inside {value_pk!r} should be of type str "
+ f"(got {type(value_pk)})",
+ params={"k": k, "values": values, "value_pk": value_pk},
+ )
class Category(MPTTModel, ModelWithMetadata, SeoModel):
@@ -142,7 +166,9 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
)
- attributes = HStoreField(default=dict, blank=True)
+ attributes = FilterableJSONBField(
+ default=dict, blank=True, validators=[validate_attribute_json]
+ )
updated_at = models.DateTimeField(auto_now=True, null=True)
charge_taxes = models.BooleanField(default=True)
weight = MeasurementField(
@@ -251,7 +277,9 @@ class ProductVariant(ModelWithMetadata):
product = models.ForeignKey(
Product, related_name="variants", on_delete=models.CASCADE
)
- attributes = HStoreField(default=dict, blank=True)
+ attributes = FilterableJSONBField(
+ default=dict, blank=True, validators=[validate_attribute_json]
+ )
images = models.ManyToManyField("ProductImage", through="VariantImage")
track_inventory = models.BooleanField(default=True)
quantity = models.IntegerField(
@@ -460,6 +488,13 @@ class AttributeQuerySet(models.QuerySet):
class Attribute(ModelWithMetadata):
slug = models.SlugField(max_length=50, unique=True)
name = models.CharField(max_length=50)
+
+ input_type = models.CharField(
+ max_length=50,
+ choices=AttributeInputType.CHOICES,
+ default=AttributeInputType.DROPDOWN,
+ )
+
product_types = models.ManyToManyField(
ProductType,
blank=True,
@@ -531,6 +566,10 @@ class AttributeValue(SortableModel):
def __str__(self):
return self.name
+ @property
+ def input_type(self):
+ return self.attribute.input_type
+
def get_ordering_queryset(self):
return self.attribute.values.all()
diff --git a/saleor/product/utils/attributes.py b/saleor/product/utils/attributes.py
index 477ae396be..d6ffc6eeb8 100644
--- a/saleor/product/utils/attributes.py
+++ b/saleor/product/utils/attributes.py
@@ -1,3 +1,7 @@
+from collections import defaultdict
+from typing import List
+
+
def get_product_attributes_data(product):
"""Return the attributes associated with the product.
@@ -26,12 +30,18 @@ def get_attributes_display_map(obj, attributes):
attributes: Attribute Iterable
"""
- display_map = {}
+ display_map = defaultdict(str)
for attribute in attributes:
- value = obj.attributes.get(str(attribute.pk))
- if value:
+ values = obj.attributes.get(str(attribute.pk)) # type: List
+ if values:
choices = {str(a.pk): a.translated for a in attribute.values.all()}
- display_map[attribute.pk] = choices[value]
+ for value in values:
+ current_display_value = display_map[attribute.pk]
+ if not current_display_value:
+ current_display_value = choices[value]
+ else:
+ current_display_value = f"{current_display_value}, {choices[value]}"
+ display_map[attribute.pk] = current_display_value
return display_map
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index 42904268a8..48414dcf61 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from decimal import Decimal
-from typing import Iterable
+from typing import Dict, Iterable, List
from django_prices.templatetags import prices_i18n
@@ -12,6 +12,23 @@ from ...seo.schema.product import variant_json_ld
from .availability import get_product_availability
+def _attributes_to_single(attributes: Dict[str, List[str]]) -> Dict[str, str]:
+ """This converts nested attributes to a flat attribute ({attr_pk: val_pk}).
+ This is used for backward compatibility between the storefront 1.0
+ and dashboard 2.0's new attribute mechanism."""
+
+ new_attributes = {}
+
+ for attr_pk, values in attributes.items():
+ if len(values) != 1:
+ # Skip multiple values - which should have been denied by the dashboard
+ continue
+
+ new_attributes[attr_pk] = values[0]
+
+ return new_attributes
+
+
def get_variant_picker_data(
product,
discounts: Iterable[DiscountInfo] = None,
@@ -50,14 +67,17 @@ def get_variant_picker_data(
"availability": in_stock,
"price": price_as_dict(price),
"priceUndiscounted": price_as_dict(price_undiscounted),
- "attributes": variant.attributes,
+ "attributes": _attributes_to_single(variant.attributes),
"priceLocalCurrency": price_as_dict(price_local_currency),
"schemaData": schema_data,
}
data["variants"].append(variant_data)
- for variant_key, variant_value in variant.attributes.items():
- filter_available_variants[int(variant_key)].append(int(variant_value))
+ for variant_key, variant_values in variant.attributes.items():
+ if len(variant_values) != 1:
+ # Skip multiple values - which should have been denied by the dashboard
+ continue
+ filter_available_variants[int(variant_key)].append(variant_values[0])
for attribute in variant_attributes:
available_variants = filter_available_variants.get(attribute.pk, None)
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index d031358260..ec73366d02 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -5,38 +5,39 @@ from django.template.defaultfilters import slugify
from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType
from saleor.graphql.product.types.attributes import resolve_attribute_value_type
-from saleor.graphql.product.utils import attributes_to_hstore
+from saleor.graphql.product.utils import attributes_to_json
+from saleor.product import AttributeInputType
from saleor.product.models import Attribute, AttributeValue, Category, ProductType
from tests.api.utils import get_graphql_content
-def test_attributes_to_hstore(product, color_attribute):
+def test_attributes_to_json(product, color_attribute):
color_value = color_attribute.values.first()
# test transforming slugs of existing attributes to IDs
- input_data = [{"slug": color_attribute.slug, "value": color_value.slug}]
+ input_data = [{"slug": color_attribute.slug, "values": [color_value.slug]}]
attrs_qs = product.product_type.product_attributes.all()
- ids = attributes_to_hstore(input_data, attrs_qs)
+ ids = attributes_to_json(input_data, attrs_qs)
assert str(color_attribute.pk) in ids
- assert ids[str(color_attribute.pk)] == str(color_value.pk)
+ assert ids[str(color_attribute.pk)] == [str(color_value.pk)]
# test creating a new attribute value
- input_data = [{"slug": color_attribute.slug, "value": "Space Grey"}]
- ids = attributes_to_hstore(input_data, attrs_qs)
+ input_data = [{"slug": color_attribute.slug, "values": ["Space Grey"]}]
+ ids = attributes_to_json(input_data, attrs_qs)
new_value = AttributeValue.objects.get(slug="space-grey")
assert str(color_attribute.pk) in ids
- assert ids[str(color_attribute.pk)] == str(new_value.pk)
+ assert ids[str(color_attribute.pk)] == [str(new_value.pk)]
# test passing an attribute that doesn't belong to this product raises
# an error
- input_data = [{"slug": "not-an-attribute", "value": "not-a-value"}]
+ input_data = [{"slug": "not-an-attribute", "values": ["not-a-value"]}]
with pytest.raises(ValueError):
- attributes_to_hstore(input_data, attrs_qs)
+ attributes_to_json(input_data, attrs_qs)
-def test_attributes_to_hstore_duplicated_slug(product, color_attribute, size_attribute):
+def test_attributes_to_json_duplicated_slug(product, color_attribute, size_attribute):
# It's possible to have a value with the same slug but for a different attribute.
- # Ensure that `attributes_to_hstore` works in that case.
+ # Ensure that `attributes_to_json` works in that case.
color_value = color_attribute.values.first()
@@ -45,11 +46,11 @@ def test_attributes_to_hstore_duplicated_slug(product, color_attribute, size_att
slug=color_value.slug, name="Duplicated value", attribute=size_attribute
)
- input_data = [{"slug": color_attribute.slug, "value": color_value.slug}]
+ input_data = [{"slug": color_attribute.slug, "values": [color_value.slug]}]
attrs_qs = product.product_type.product_attributes.all()
- ids = attributes_to_hstore(input_data, attrs_qs)
+ ids = attributes_to_json(input_data, attrs_qs)
assert str(color_attribute.pk) in ids
- assert ids[str(color_attribute.pk)] == str(color_value.pk)
+ assert ids[str(color_attribute.pk)] == [str(color_value.pk)]
def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values):
@@ -791,6 +792,45 @@ def test_assign_variant_attribute_to_product_type_with_disabled_variants(
]
+def test_assign_variant_attribute_having_unsupported_input_type(
+ staff_api_client, permission_manage_products, product_type, size_attribute
+):
+ """The assignAttribute mutation should raise an error when trying
+ to use an attribute as a variant attribute when
+ the attribute's input type doesn't support variants"""
+
+ attribute = size_attribute
+ attribute.input_type = AttributeInputType.MULTISELECT
+ attribute.save(update_fields=["input_type"])
+ product_type.variant_attributes.clear()
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = ASSIGN_ATTR_QUERY
+ operations = [
+ {
+ "attributeType": "VARIANT",
+ "attributeId": graphene.Node.to_global_id("Attribute", attribute.pk),
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["attributeAssign"]
+ assert content["errors"] == [
+ {
+ "field": "operations",
+ "message": (
+ "Attributes having for input types ['multiselect'] cannot be assigned "
+ "as variant attributes"
+ ),
+ }
+ ]
+
+
@pytest.mark.parametrize(
"product_type_attribute_type, gql_attribute_type",
(
@@ -938,3 +978,33 @@ def test_unassign_attributes_not_in_product_type(
assert content["productType"]["id"] == product_type_global_id
assert len(content["productType"]["productAttributes"]) == 0
assert len(content["productType"]["variantAttributes"]) == 0
+
+
+def test_retrieve_product_attributes_input_type(
+ staff_api_client, product, permission_manage_products
+):
+ query = """
+ {
+ products(first: 10) {
+ edges {
+ node {
+ attributes {
+ value {
+ type
+ inputType
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+
+ found_products = get_graphql_content(
+ staff_api_client.post_graphql(query, permissions=[permission_manage_products])
+ )["data"]["products"]["edges"]
+ assert len(found_products) == 1
+
+ for gql_attr in found_products[0]["node"]["attributes"]:
+ assert gql_attr["value"]["type"] == "STRING"
+ assert gql_attr["value"]["inputType"] == "DROPDOWN"
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 2278a4b454..9f7f518089 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -16,6 +16,7 @@ from saleor.extensions.manager import ExtensionsManager
from saleor.graphql.core.enums import ReportingPeriod
from saleor.graphql.product.enums import StockAvailability
from saleor.graphql.product.types.products import resolve_attribute_list
+from saleor.product import AttributeInputType
from saleor.product.models import (
Attribute,
AttributeValue,
@@ -69,17 +70,17 @@ def query_collections_with_filter():
def test_resolve_attribute_list(color_attribute):
value = color_attribute.values.first()
- attributes_hstore = {str(color_attribute.pk): str(value.pk)}
- res = resolve_attribute_list(attributes_hstore, Attribute.objects.all())
+ attributes_json = {str(color_attribute.pk): [str(value.pk)]}
+ res = resolve_attribute_list(attributes_json, Attribute.objects.all())
assert len(res) == 1
assert res[0].attribute.name == color_attribute.name
assert res[0].value.name == value.name
- # test passing invalid hstore should resolve to empty list
+ # test passing invalid json should resolve to empty list
attr_pk = str(Attribute.objects.order_by("pk").last().pk + 1)
val_pk = str(AttributeValue.objects.order_by("pk").last().pk + 1)
- attributes_hstore = {attr_pk: val_pk}
- res = resolve_attribute_list(attributes_hstore, Attribute.objects.all())
+ attributes_json = {attr_pk: [val_pk]}
+ res = resolve_attribute_list(attributes_json, Attribute.objects.all())
assert res == []
@@ -255,7 +256,7 @@ def test_products_query_with_filter_attributes(
second_product = product
second_product.id = None
second_product.product_type = product_type
- second_product.attributes = {smart_text(attribute.pk): smart_text(attr_value.pk)}
+ second_product.attributes = {smart_text(attribute.pk): [smart_text(attr_value.pk)]}
second_product.save()
variables = {
@@ -774,8 +775,8 @@ def test_create_product(
"taxCode": product_tax_rate,
"basePrice": product_price,
"attributes": [
- {"slug": color_attr_slug, "value": color_value_slug},
- {"slug": size_attr_slug, "value": non_existent_attr_value},
+ {"slug": color_attr_slug, "values": [color_value_slug]},
+ {"slug": size_attr_slug, "values": [non_existent_attr_value]},
],
}
@@ -1097,6 +1098,55 @@ def test_update_product(
assert not data["product"]["category"]["name"] == category.name
+SET_ATTRIBUTES_TO_PRODUCT_QUERY = """
+ mutation updateProduct($productId: ID!, $attributes: [AttributeValueInput!]) {
+ productUpdate(id: $productId, input: { attributes: $attributes }) {
+ errors {
+ message
+ field
+ }
+ }
+ }
+"""
+
+
+def test_update_product_can_only_assign_multiple_values_to_valid_input_types(
+ staff_api_client, product, permission_manage_products, color_attribute
+):
+ """Ensures you cannot assign multiple values to input types
+ that are not multi-select. This also ensures multi-select types
+ can be assigned multiple values as intended."""
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ multi_values_attr = Attribute.objects.create(
+ name="multi", slug="multi-vals", input_type=AttributeInputType.MULTISELECT
+ )
+ multi_values_attr.product_types.add(product.product_type)
+
+ # Try to assign multiple values from an attribute that does not support such things
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product.pk),
+ "attributes": [{"slug": color_attribute.slug, "values": ["red", "blue"]}],
+ }
+ data = get_graphql_content(
+ staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
+ )["data"]["productUpdate"]
+ assert data["errors"] == [
+ {
+ "field": "attributes",
+ "message": "A dropdown attribute must take only one value",
+ }
+ ]
+
+ # Try to assign multiple values from a valid attribute
+ variables["attributes"] = [{"slug": multi_values_attr.slug, "values": ["a", "b"]}]
+ data = get_graphql_content(
+ staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
+ )["data"]["productUpdate"]
+ assert data["errors"] == []
+
+
def test_update_product_without_variants(
staff_api_client, product_with_default_variant, permission_manage_products
):
diff --git a/tests/api/test_variant.py b/tests/api/test_variant.py
index e26d6abd6c..135d1562da 100644
--- a/tests/api/test_variant.py
+++ b/tests/api/test_variant.py
@@ -126,7 +126,7 @@ def test_create_variant(
"costPrice": cost_price,
"priceOverride": price_override,
"weight": weight,
- "attributes": [{"slug": variant_slug, "value": variant_value}],
+ "attributes": [{"slug": variant_slug, "values": [variant_value]}],
"trackInventory": True,
}
response = staff_api_client.post_graphql(
@@ -176,7 +176,7 @@ def test_create_product_variant_not_all_attributes(
variables = {
"productId": product_id,
"sku": sku,
- "attributes": [{"slug": variant_slug, "value": variant_value}],
+ "attributes": [{"slug": variant_slug, "values": [variant_value]}],
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
@@ -277,7 +277,7 @@ def test_update_product_variant_not_all_attributes(
variables = {
"id": variant_id,
"sku": sku,
- "attributes": [{"slug": variant_slug, "value": variant_value}],
+ "attributes": [{"slug": variant_slug, "values": [variant_value]}],
}
response = staff_api_client.post_graphql(
diff --git a/tests/conftest.py b/tests/conftest.py
index 90fc8fe0a9..cd3b17baa3 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -32,6 +32,7 @@ from saleor.order.utils import fulfill_order_line, recalculate_order
from saleor.page.models import Page
from saleor.payment import ChargeStatus, TransactionKind
from saleor.payment.models import Payment
+from saleor.product import AttributeInputType
from saleor.product.models import (
Attribute,
AttributeTranslation,
@@ -385,7 +386,7 @@ def categories_tree(db, product_type): # pylint: disable=W0613
product_attr = product_type.product_attributes.first()
attr_value = product_attr.values.first()
- attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
+ attributes = {smart_text(product_attr.pk): [smart_text(attr_value.pk)]}
Product.objects.create(
name="Test product",
@@ -440,7 +441,7 @@ def product_type_without_variant():
def product(product_type, category):
product_attr = product_type.product_attributes.first()
attr_value = product_attr.values.first()
- attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
+ attributes = {smart_text(product_attr.pk): [smart_text(attr_value.pk)]}
product = Product.objects.create(
name="Test product",
@@ -453,7 +454,7 @@ def product(product_type, category):
variant_attr = product_type.variant_attributes.first()
variant_attr_value = variant_attr.values.first()
variant_attributes = {
- smart_text(variant_attr.pk): smart_text(variant_attr_value.pk)
+ smart_text(variant_attr.pk): [smart_text(variant_attr_value.pk)]
}
ProductVariant.objects.create(
@@ -467,6 +468,34 @@ def product(product_type, category):
return product
+def variant_with_multiple_values_attributes(
+ variant, product_type, category
+) -> ProductVariant:
+ variant_attr = Attribute.objects.create(
+ slug="modes", name="Available Modes", input_type=AttributeInputType.MULTISELECT
+ )
+
+ attr_val_1 = AttributeValue.objects.create(
+ attribute=variant_attr, name="Eco Mode", slug="eco"
+ )
+ attr_val_2 = AttributeValue.objects.create(
+ attribute=variant_attr, name="Performance Mode", slug="power"
+ )
+
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(variant_attr)
+
+ variant.attributes = {
+ smart_text(variant_attr.pk): [
+ smart_text(attr_val_1.pk),
+ smart_text(attr_val_2.pk),
+ ]
+ }
+ variant.save(update_fields=["attributes"])
+ return variant
+
+
@pytest.fixture
def product_with_default_variant(product_type_without_variant, category):
product = Product.objects.create(
@@ -525,7 +554,7 @@ def product_without_shipping(category):
def product_list(product_type, category):
product_attr = product_type.product_attributes.first()
attr_value = product_attr.values.first()
- attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
+ attributes = {smart_text(product_attr.pk): [smart_text(attr_value.pk)]}
products = Product.objects.bulk_create(
[
@@ -643,7 +672,7 @@ def unavailable_product_with_variant(product_type, category):
variant_attr = product_type.variant_attributes.first()
variant_attr_value = variant_attr.values.first()
variant_attributes = {
- smart_text(variant_attr.pk): smart_text(variant_attr_value.pk)
+ smart_text(variant_attr.pk): [smart_text(variant_attr_value.pk)]
}
ProductVariant.objects.create(
diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.py
index 1c5a024722..d0374ec04a 100644
--- a/tests/dashboard/test_product.py
+++ b/tests/dashboard/test_product.py
@@ -1074,11 +1074,11 @@ def test_product_form_change_attributes(db, product, color_attribute):
assert form.is_valid()
product = form.save()
- assert product.attributes[str(color_attribute.pk)] == str(color_value.pk)
+ assert product.attributes[str(color_attribute.pk)] == [str(color_value.pk)]
# Check that new attribute was created for author
author_value = AttributeValue.objects.get(name=new_author)
- assert product.attributes[str(text_attribute.pk)] == str(author_value.pk)
+ assert product.attributes[str(text_attribute.pk)] == [str(author_value.pk)]
def test_product_form_assign_collection_to_product(product):
diff --git a/tests/test_product.py b/tests/test_product.py
index eefc092b07..f9c8534ca5 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
import pytest
from django.core import serializers
+from django.core.exceptions import ValidationError
from django.core.serializers.base import DeserializationError
from django.http import JsonResponse
from django.urls import reverse
@@ -20,7 +21,7 @@ from saleor.checkout.utils import add_variant_to_checkout
from saleor.menu.models import MenuItemTranslation
from saleor.menu.utils import update_menu
from saleor.product import ProductAvailabilityStatus, models
-from saleor.product.models import DigitalContentUrl
+from saleor.product.models import DigitalContentUrl, validate_attribute_json
from saleor.product.thumbnails import create_product_thumbnails
from saleor.product.utils import (
allocate_stock,
@@ -102,9 +103,9 @@ def test_filtering_by_attribute(db, color_attribute, category, settings):
variant_b = models.ProductVariant.objects.create(product=product_b, sku="12345")
color = color_attribute.values.first()
color_2 = color_attribute.values.last()
- product_a.attributes[str(color_attribute.pk)] = str(color.pk)
+ product_a.attributes[str(color_attribute.pk)] = [str(color.pk)]
product_a.save()
- variant_b.attributes[str(color_attribute.pk)] = str(color.pk)
+ variant_b.attributes[str(color_attribute.pk)] = [str(color.pk)]
variant_b.save()
filtered = filter_products_by_attribute(
@@ -113,7 +114,7 @@ def test_filtering_by_attribute(db, color_attribute, category, settings):
assert product_a in list(filtered)
assert product_b in list(filtered)
- product_a.attributes[str(color_attribute.pk)] = str(color_2.pk)
+ product_a.attributes[str(color_attribute.pk)] = [str(color_2.pk)]
product_a.save()
filtered = filter_products_by_attribute(
models.Product.objects.all(), color_attribute.pk, color.pk
@@ -476,6 +477,20 @@ def test_get_variant_picker_data_proper_variant_count(product):
assert len(data["variantAttributes"][0]["values"]) == 1
+def test_get_variant_picker_data_no_nested_attributes(
+ variant_with_multiple_values_attributes
+):
+ """Ensures that if someone bypassed variant attributes checks (e.g. a raw SQL query)
+ and inserted an attribute with multiple values, it doesn't return invalid data
+ to the storefront that would crash it."""
+ product = variant_with_multiple_values_attributes.product
+ data = get_variant_picker_data(
+ product, discounts=None, taxes=None, local_currency=None
+ )
+
+ assert len(data["variantAttributes"]) == 0
+
+
def test_render_product_page_with_no_variant(unavailable_product, admin_client):
product = unavailable_product
product.is_published = True
@@ -878,3 +893,28 @@ def test_costs_get_margin_for_variant(variant, price, cost):
variant.cost_price = cost
variant.price_override = price
assert not get_margin_for_variant(variant)
+
+
+ "value, error",
+ (
+ ({123: []}, ["The key 123 should be of type str (got <class 'int'>)"]),
+ (
+ {"123": 111},
+ ["The values of '123' should be of type list (got <class 'int'>)"],
+ ),
+ (
+ {"123": [111]},
+ ["The values inside 111 should be of type str (got <class 'int'>)"],
+ ),
+ ),
+)
+def test_product_attributes_validator_invalid_values(value, error):
+ with pytest.raises(ValidationError) as exc_info:
+ validate_attribute_json(value)
+ assert exc_info.value.args[0] == error
+
+
[email protected]("value", ({"123": []}, {"123": ["111"]}))
+def test_product_attributes_validator_accept_valid_values(value):
+ validate_attribute_json(value)
diff --git a/tests/utils.py b/tests/utils.py
index f506a20eb8..762599e512 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -21,8 +21,8 @@ def get_redirect_location(response):
def filter_products_by_attribute(queryset, attribute_id, value):
key = smart_text(attribute_id)
value = smart_text(value)
- in_product = Q(attributes__contains={key: value})
- in_variant = Q(variants__attributes__contains={key: value})
+ in_product = Q(**{f"attributes__from_key_{key}__has_key": value})
+ in_variant = Q(**{f"variants__attributes__from_key_{key}__has_key": value})
return queryset.filter(in_product | in_variant)