Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Products and variants now returns attributes with the custom order
NyanKiyoshif9051008b139
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex 75673624ba..e6ee96ea57 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -60,9 +60,9 @@ def resolve_attributes(if sort_by:is_asc = sort_by["direction"] == OrderDirection.ASC.valueif sort_by["field"] == AttributeSortField.DASHBOARD_VARIANT_POSITION.value:- qs = qs.variant_attributes_sorted_for_dashboard(is_asc)+ qs = qs.variant_attributes_sorted(is_asc)elif sort_by["field"] == AttributeSortField.DASHBOARD_PRODUCT_POSITION.value:- qs = qs.product_attributes_sorted_for_dashboard(is_asc)+ qs = qs.product_attributes_sorted(is_asc)else:qs = sort_qs(qs, sort_by)else:diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 788c125811..00c05b558f 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -1,3 +1,4 @@+from collections import OrderedDictfrom typing import Dictimport graphene@@ -81,7 +82,7 @@ def resolve_attribute_list(attributes_json, attributes_qs):`attributes_qs` is the queryset of attribute objects. If it's prefetchbeforehand along with the values, it saves database queries."""- attributes_map = {} # type: Dict[str, models.Attribute]+ attributes_map = OrderedDict() # type: Dict[str, models.Attribute]values_map = {} # type: Dict[str, models.AttributeValue]for attr in attributes_qs:attributes_map[str(attr.pk)] = attr@@ -277,7 +278,7 @@ class ProductVariant(CountableDjangoObjectType, MetadataObjectType):def resolve_attributes(root: models.ProductVariant, info):attr_qs = root.product.product_type.variant_attributes.get_visible_to_user(info.context.user- )+ ).variant_attributes_sorted()return resolve_attribute_list(root.attributes, attr_qs)@staticmethod@@ -561,7 +562,7 @@ class Product(CountableDjangoObjectType, MetadataObjectType):def resolve_attributes(root: models.Product, info):attributes_qs = root.product_type.product_attributes.get_visible_to_user(info.context.user- )+ ).product_attributes_sorted()return resolve_attribute_list(root.attributes, attributes_qs)@staticmethod@@ -679,14 +680,14 @@ class ProductType(CountableDjangoObjectType, MetadataObjectType):prefetch_related="product_attributes__attributeproduct")def resolve_product_attributes(root: models.ProductType, *_args, **_kwargs):- return root.product_attributes.product_attributes_sorted_for_dashboard().all()+ return root.product_attributes.product_attributes_sorted().all()@staticmethod@gql_optimizer.resolver_hints(prefetch_related="variant_attributes__attributevariant")def resolve_variant_attributes(root: models.ProductType, *_args, **_kwargs):- return root.variant_attributes.variant_attributes_sorted_for_dashboard().all()+ return root.variant_attributes.variant_attributes_sorted().all()@staticmethoddef resolve_products(root: models.ProductType, info, **_kwargs):diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 9e5e713e42..14d428df7f 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -523,10 +523,10 @@ class AttributeQuerySet(models.QuerySet):return self.order_by(sort_method, id_sort)- def product_attributes_sorted_for_dashboard(self, asc=True):+ def product_attributes_sorted(self, asc=True):return self._get_sorted_m2m_field("attributeproduct", asc)- def variant_attributes_sorted_for_dashboard(self, asc=True):+ def variant_attributes_sorted(self, asc=True):return self._get_sorted_m2m_field("attributevariant", asc)diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex db5d2cb141..a1a04e4fa0 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -1817,3 +1817,87 @@ def test_sort_attributes_by_default_sorting(api_client):assert len(attributes) == 2assert attributes[0]["node"]["slug"] == "b"assert attributes[1]["node"]["slug"] == "a"++[email protected]("is_variant", (True, False))+def test_attributes_of_products_are_sorted(+ staff_api_client, product, color_attribute, is_variant+):+ """Ensures the attributes of products and variants are sorted."""++ variant = product.variants.first()++ if is_variant:+ query = """+ query($id: ID!) {+ productVariant(id: $id) {+ attributes {+ attribute {+ id+ }+ }+ }+ }+ """+ else:+ query = """+ query($id: ID!) {+ product(id: $id) {+ attributes {+ attribute {+ id+ }+ }+ }+ }+ """++ # Create a dummy attribute with a higher ID+ # This will allow us to make sure it is always the last attribute+ # when sorted by ID. Thus, we are sure the query is actually passing the test.+ other_attribute = Attribute.objects.create(name="Other", slug="other")++ # Add the attribute to the product type+ if is_variant:+ product.product_type.variant_attributes.set([color_attribute, other_attribute])+ else:+ product.product_type.product_attributes.set([color_attribute, other_attribute])++ # Retrieve the M2M object for the attribute vs the product type+ if is_variant:+ m2m_rel_other_attr = other_attribute.attributevariant.last()+ else:+ m2m_rel_other_attr = other_attribute.attributeproduct.last()++ # Push the last attribute to the top and let the others to None+ m2m_rel_other_attr.sort_order = 0+ m2m_rel_other_attr.save(update_fields=["sort_order"])++ # Assign attributes to the product+ node = variant if is_variant else product+ node.attributes = {+ str(color_attribute.pk): [str(color_attribute.values.first().pk)]+ }+ node.save(update_fields=["attributes"])++ # Sort the database attributes by their sort order and ID (when None)+ expected_order = [other_attribute.pk, color_attribute.pk]++ # Make the node ID+ if is_variant:+ node_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ else:+ node_id = graphene.Node.to_global_id("Product", product.pk)++ # Retrieve the attributes+ data = get_graphql_content(staff_api_client.post_graphql(query, {"id": node_id}))[+ "data"+ ]+ attributes = data["productVariant" if is_variant else "product"]["attributes"]+ actual_order = [+ int(graphene.Node.from_global_id(attr["attribute"]["id"])[1])+ for attr in attributes+ ]++ # Compare the received data against our expectations+ assert actual_order == expected_order