Skip to content

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

Implement product sorting by attribute

NyanKiyoshi11fe2e3b714f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3539d8519a..544ba74b74 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -71,6 +71,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Added validations for minimum password length in settings - #4735 by @fowczarek
- Add error codes to mutations responses - #4676 by @Kwaidan00
- Payment gateways are now saleor plugins with dynamic configuration - #4669 by @salwator
+- Added support for sorting product by their attribute values through given attribute ID - #4740 by @NyanKiyoshi
## 2.8.0
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 1fe8a346dd..342b5eeb40 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -1,10 +1,14 @@
+from typing import TYPE_CHECKING, Optional
+
import graphene
import graphene_django_optimizer as gql_optimizer
from django.db.models import Q, Sum
+from graphql import GraphQLError
from ...order import OrderStatus
from ...product import models
from ...search.backends import picker
+from ..core.utils import from_global_id_strict_type
from ..utils import filter_by_period, filter_by_query_param, get_database_id, get_nodes
from .enums import AttributeSortField, OrderDirection
from .filters import (
@@ -17,6 +21,9 @@ from .filters import (
sort_qs,
)
+if TYPE_CHECKING:
+ from ..product.types import ProductOrder # noqa
+
PRODUCT_SEARCH_FIELDS = ("name", "description")
PRODUCT_TYPE_SEARCH_FIELDS = ("name",)
CATEGORY_SEARCH_FIELDS = ("name", "slug", "description", "parent__name")
@@ -102,6 +109,29 @@ def resolve_digital_contents(info):
return gql_optimizer.query(qs, info)
+def sort_products(qs: models.ProductsQueryset, sort_by: Optional["ProductOrder"]):
+ if sort_by is None:
+ return qs
+
+ # Check if one of the required fields was provided
+ if sort_by.field and sort_by.attribute_id:
+ raise GraphQLError(
+ ("You must provide either `field` or `attributeId` to sort the products.")
+ )
+
+ direction = sort_by.direction
+ sorting_field = sort_by.field
+
+ if sort_by.attribute_id:
+ is_ascending = direction == OrderDirection.ASC
+ attribute_pk = from_global_id_strict_type(sort_by.attribute_id, "Attribute")
+ qs = qs.sort_by_attribute(attribute_pk, ascending=is_ascending)
+ else:
+ qs = qs.order_by(f"{direction}{sorting_field}")
+
+ return qs
+
+
def resolve_products(
info,
attributes=None,
@@ -119,6 +149,7 @@ def resolve_products(
user = info.context.user
qs = models.Product.objects.visible_to_user(user)
+ qs = sort_products(qs, sort_by)
if query:
search = picker.pick_backend()
@@ -140,7 +171,6 @@ def resolve_products(
qs = filter_products_by_price(qs, price_lte, price_gte)
qs = filter_products_by_minimal_price(qs, minimal_price_lte, minimal_price_gte)
- qs = sort_qs(qs, sort_by)
qs = qs.distinct()
return gql_optimizer.query(qs, info)
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 4a07f0dd85..f4623fe38f 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -127,9 +127,14 @@ def resolve_attribute_list(
class ProductOrder(graphene.InputObjectType):
field = graphene.Argument(
- ProductOrderField,
- required=True,
- description="Sort products by the selected field.",
+ ProductOrderField, description="Sort products by the selected field."
+ )
+ attribute_id = graphene.Argument(
+ graphene.ID,
+ description=(
+ "Sort product by the selected attribute's values.\n"
+ "Note: this doesn't take translations into account yet."
+ ),
)
direction = graphene.Argument(
OrderDirection,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index f086b8d379..d8f04ab132 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2979,7 +2979,8 @@ input ProductInput {
}
input ProductOrder {
- field: ProductOrderField!
+ field: ProductOrderField
+ attributeId: ID
direction: OrderDirection!
}
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 5269016186..6739dee6e6 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -1,12 +1,13 @@
from decimal import Decimal
-from typing import Iterable
+from typing import Iterable, Union
from uuid import uuid4
from django.conf import settings
+from django.contrib.postgres.aggregates import StringAgg
from django.contrib.postgres.fields import JSONField
from django.core.validators import MinValueValidator
from django.db import models
-from django.db.models import F, Q
+from django.db.models import Case, Count, F, FilteredRelation, Q, When
from django.urls import reverse
from django.utils.encoding import smart_text
from django.utils.html import strip_tags
@@ -157,6 +158,81 @@ class ProductsQueryset(PublishedQuerySet):
)
return qs
+ def sort_by_attribute(self, attribute_pk: Union[int, str], ascending: bool = True):
+ """Sort a query set by the values of the given product attribute.
+
+ :param attribute_pk: The database ID (must be a number) of the attribute
+ to sort by.
+ :param ascending: The sorting direction.
+ """
+ qs: models.QuerySet = self
+
+ # Retrieve all the products' attribute data IDs (assignments) and
+ # product types that have the given attribute associated to them
+ attribute_associations, product_types_associated_to_attribute = zip(
+ *AttributeProduct.objects.filter(attribute_id=attribute_pk).values_list(
+ "pk", "product_type_id"
+ )
+ )
+
+ qs = qs.annotate(
+ # Contains to retrieve the attribute data (singular) of each product
+ # Refer to `AttributeProduct`.
+ filtered_attribute=FilteredRelation(
+ relation_name="attributes",
+ condition=Q(attributes__assignment_id__in=attribute_associations),
+ ),
+ # Implicit `GROUP BY` required for the `StringAgg` aggregation
+ grouped_ids=Count("id"),
+ # String aggregation of the attribute's values to efficiently sort them
+ concatenated_values=Case(
+ # If the product has no association data but has the given attribute
+ # associated to its product type, then consider the concatenated values
+ # as empty (non-null).
+ When(
+ Q(product_type_id__in=product_types_associated_to_attribute)
+ & Q(filtered_attribute=None),
+ then=models.Value(""),
+ ),
+ default=StringAgg(
+ F("filtered_attribute__values__name"),
+ delimiter=",",
+ ordering=(
+ [
+ f"filtered_attribute__values__{field_name}"
+ for field_name in AttributeValue._meta.ordering
+ ]
+ ),
+ ),
+ output_field=models.CharField(),
+ ),
+ )
+
+ qs = qs.extra(
+ order_by=[
+ Case(
+ # Make the products having no such attribute be last in the sorting
+ When(concatenated_values=None, then=2),
+ # Put the products having an empty attribute value at the bottom of
+ # the other products.
+ When(concatenated_values="", then=1),
+ # Put the products having an attribute value to be always at the top
+ default=0,
+ output_field=models.IntegerField(),
+ ),
+ # Sort each group of products (0, 1, 2, ...) per attribute values
+ "concatenated_values",
+ # Sort each group of products by name,
+ # if they have the same values or not values
+ "name",
+ ]
+ )
+
+ # Descending sorting
+ if not ascending:
+ return qs.reverse()
+ return qs
+
class Product(SeoModel, ModelWithMetadata, PublishableModel):
product_type = models.ForeignKey(
diff --git a/tests/api/benchmark/test_product.py b/tests/api/benchmark/test_product.py
index 8d111bc27d..57ff1d17c9 100644
--- a/tests/api/benchmark/test_product.py
+++ b/tests/api/benchmark/test_product.py
@@ -91,3 +91,27 @@ def test_product_details(product, api_client, count_queries):
variables = {"id": Node.to_global_id("Product", product.pk)}
get_graphql_content(api_client.post_graphql(query, variables))
+
+
[email protected]_queries(autouse=False)
+def test_retrieve_product_attributes(product_list, api_client, count_queries):
+ query = """
+ query($sortBy: ProductOrder) {
+ products(first: 10, sortBy: $sortBy) {
+ edges {
+ node {
+ id
+ attributes {
+ attribute {
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+
+ variables = {}
+ get_graphql_content(api_client.post_graphql(query, variables))
diff --git a/tests/api/test_product_sorting.py b/tests/api/test_product_sorting.py
index 8b13b9f0d2..9108a0460b 100644
--- a/tests/api/test_product_sorting.py
+++ b/tests/api/test_product_sorting.py
@@ -1,6 +1,6 @@
import graphene
-from tests.api.utils import get_graphql_content
+from ..api.utils import get_graphql_content
GET_SORTED_PRODUCTS_COLLECTION_QUERY = """
query CollectionProducts($id: ID!) {
diff --git a/tests/api/test_product_sorting_attributes.py b/tests/api/test_product_sorting_attributes.py
new file mode 100644
index 0000000000..9b2467fa9f
--- /dev/null
+++ b/tests/api/test_product_sorting_attributes.py
@@ -0,0 +1,505 @@
+import os.path
+
+import graphene
+import pytest
+
+from saleor.core.taxes import zero_money
+from saleor.product import models as product_models
+from saleor.product.utils.attributes import associate_attribute_values_to_instance
+
+from ..api.utils import get_graphql_content
+
+HERE = os.path.realpath(os.path.dirname(__file__))
+
+QUERY_SORT_PRODUCTS_BY_ATTRIBUTE = """
+query products(
+ $field: ProductOrderField
+ $attributeId: ID
+ $direction: OrderDirection!
+) {
+ products(
+ first: 100
+ sortBy: { field: $field, attributeId: $attributeId, direction: $direction }
+ ) {
+ edges {
+ node {
+ name
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ name
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+COLORS = (["Blue", "Red"], ["Blue", "Gray"], ["Pink"], ["Pink"], ["Green"])
+TRADEMARKS = ("A", "A", "ab", "b", "y")
+DUMMIES = ("Oopsie",)
+
+
+def products_structures(category):
+ def attr_value(attribute, *values):
+ return [attribute.values.get_or_create(name=v, slug=v)[0] for v in values]
+
+ assert product_models.Product.objects.count() == 0
+
+ in_multivals = product_models.AttributeInputType.MULTISELECT
+
+ pt_apples, pt_oranges, pt_other = list(
+ product_models.ProductType.objects.bulk_create(
+ [
+ product_models.ProductType(name="Apples", has_variants=False),
+ product_models.ProductType(name="Oranges", has_variants=False),
+ product_models.ProductType(name="Other attributes", has_variants=False),
+ ]
+ )
+ )
+
+ colors_attr, trademark_attr, dummy_attr = list(
+ product_models.Attribute.objects.bulk_create(
+ [
+ product_models.Attribute(
+ name="Colors", slug="colors", input_type=in_multivals
+ ),
+ product_models.Attribute(name="Trademark", slug="trademark"),
+ product_models.Attribute(name="Dummy", slug="dummy"),
+ ]
+ )
+ )
+
+ # Manually add every attribute to given product types
+ # to force the preservation of ordering
+ pt_apples.product_attributes.add(colors_attr)
+ pt_apples.product_attributes.add(trademark_attr)
+
+ pt_oranges.product_attributes.add(colors_attr)
+ pt_oranges.product_attributes.add(trademark_attr)
+
+ pt_other.product_attributes.add(dummy_attr)
+
+ assert len(COLORS) == len(TRADEMARKS)
+
+ apples = list(
+ product_models.Product.objects.bulk_create(
+ [
+ product_models.Product(
+ name=f"{attrs[0]} Apple - {attrs[1]} ({i})",
+ product_type=pt_apples,
+ category=category,
+ price=zero_money(),
+ is_published=True,
+ )
+ for i, attrs in enumerate(zip(COLORS, TRADEMARKS))
+ ]
+ )
+ )
+
+ oranges = list(
+ product_models.Product.objects.bulk_create(
+ [
+ product_models.Product(
+ name=f"{attrs[0]} Orange - {attrs[1]} ({i})",
+ product_type=pt_oranges,
+ category=category,
+ price=zero_money(),
+ is_published=True,
+ )
+ for i, attrs in enumerate(zip(COLORS, TRADEMARKS))
+ ]
+ )
+ )
+
+ dummy = product_models.Product.objects.create(
+ name=f"Oopsie Dummy",
+ product_type=pt_other,
+ category=category,
+ price=zero_money(),
+ is_published=True,
+ )
+ product_models.Product.objects.create(
+ name=f"Another Dummy but first in ASC and has no attribute value",
+ product_type=pt_other,
+ category=category,
+ price=zero_money(),
+ is_published=True,
+ )
+ dummy_attr_value = attr_value(dummy_attr, DUMMIES[0])
+ associate_attribute_values_to_instance(dummy, dummy_attr, *dummy_attr_value)
+
+ for products in (apples, oranges):
+ for product, attr_values in zip(products, COLORS):
+ attr_values = attr_value(colors_attr, *attr_values)
+ associate_attribute_values_to_instance(product, colors_attr, *attr_values)
+
+ for product, attr_values in zip(products, TRADEMARKS):
+ attr_values = attr_value(trademark_attr, attr_values)
+ associate_attribute_values_to_instance(
+ product, trademark_attr, *attr_values
+ )
+
+ return colors_attr, trademark_attr, dummy_attr
+
+
+def test_sort_products_cannot_sort_both_by_field_and_by_attribute(api_client):
+ """Ensure one cannot both sort by a supplied field and sort by a given attribute ID
+ at the same time.
+ """
+ query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE
+ variables = {"field": "NAME", "attributeId": "SomeAttributeId", "direction": "ASC"}
+
+ response = api_client.post_graphql(query, variables)
+ response = get_graphql_content(response, ignore_errors=True)
+
+ errors = response.get("errors", [])
+
+ assert len(errors) == 1, response
+ assert errors[0]["message"] == (
+ "You must provide either `field` or `attributeId` to sort the products."
+ )
+
+
+# Ordered by the given attribute value, then by the product name.
+#
+# If the product doesn't have a value, it will be placed at the bottom of the products
+# having a value and will be ordered by their product name.
+#
+# If the product doesn't have such attribute in its product type, it will be placed
+# at the end of the other products having such attribute. They will be ordered by their
+# name as well.
+EXPECTED_SORTED_DATA_SINGLE_VALUE_ASC = [
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Gray"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Gray'] Apple - A (1)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Gray"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Gray'] Orange - A (1)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Red"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Red'] Apple - A (0)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Red"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Red'] Orange - A (0)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "ab"}]},
+ ],
+ "name": "['Pink'] Apple - ab (2)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "ab"}]},
+ ],
+ "name": "['Pink'] Orange - ab (2)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "b"}]},
+ ],
+ "name": "['Pink'] Apple - b (3)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "b"}]},
+ ],
+ "name": "['Pink'] Orange - b (3)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Green"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "y"}]},
+ ],
+ "name": "['Green'] Apple - y (4)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Green"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "y"}]},
+ ],
+ "name": "['Green'] Orange - y (4)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [{"attribute": {"slug": "dummy"}, "values": []}],
+ "name": "Another Dummy but first in ASC and has no attribute " "value",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "dummy"}, "values": [{"name": "Oopsie"}]}
+ ],
+ "name": "Oopsie Dummy",
+ }
+ },
+]
+
+EXPECTED_SORTED_DATA_MULTIPLE_VALUES_ASC = [
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Gray"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Gray'] Apple - A (1)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Gray"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Gray'] Orange - A (1)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Red"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Red'] Apple - A (0)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {
+ "attribute": {"slug": "colors"},
+ "values": [{"name": "Blue"}, {"name": "Red"}],
+ },
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "A"}]},
+ ],
+ "name": "['Blue', 'Red'] Orange - A (0)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Green"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "y"}]},
+ ],
+ "name": "['Green'] Apple - y (4)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Green"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "y"}]},
+ ],
+ "name": "['Green'] Orange - y (4)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "ab"}]},
+ ],
+ "name": "['Pink'] Apple - ab (2)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "b"}]},
+ ],
+ "name": "['Pink'] Apple - b (3)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "ab"}]},
+ ],
+ "name": "['Pink'] Orange - ab (2)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "colors"}, "values": [{"name": "Pink"}]},
+ {"attribute": {"slug": "trademark"}, "values": [{"name": "b"}]},
+ ],
+ "name": "['Pink'] Orange - b (3)",
+ }
+ },
+ {
+ "node": {
+ "attributes": [{"attribute": {"slug": "dummy"}, "values": []}],
+ "name": "Another Dummy but first in ASC and has no attribute " "value",
+ }
+ },
+ {
+ "node": {
+ "attributes": [
+ {"attribute": {"slug": "dummy"}, "values": [{"name": "Oopsie"}]}
+ ],
+ "name": "Oopsie Dummy",
+ }
+ },
+]
+
+
[email protected]("ascending", [True, False])
+def test_sort_product_by_attribute_single_value(
+ api_client, products_structures, ascending
+):
+ _, attribute, _ = products_structures
+ attribute_id: str = graphene.Node.to_global_id("Attribute", attribute.pk)
+ direction = "ASC" if ascending else "DESC"
+
+ query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE
+ variables = {"attributeId": attribute_id, "direction": direction}
+
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+ products = response["data"]["products"]["edges"]
+
+ assert len(products) == product_models.Product.objects.count()
+
+ if ascending:
+ assert products == EXPECTED_SORTED_DATA_SINGLE_VALUE_ASC
+ else:
+ assert products == list(reversed(EXPECTED_SORTED_DATA_SINGLE_VALUE_ASC))
+
+
[email protected]("ascending", [True, False])
+def test_sort_product_by_attribute_multiple_values(
+ api_client, products_structures, ascending
+):
+ attribute, _, _ = products_structures
+ attribute_id: str = graphene.Node.to_global_id("Attribute", attribute.pk)
+ direction = "ASC" if ascending else "DESC"
+
+ query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE
+ variables = {"attributeId": attribute_id, "direction": direction}
+
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+ products = response["data"]["products"]["edges"]
+
+ assert len(products) == product_models.Product.objects.count()
+
+ if ascending:
+ assert products == EXPECTED_SORTED_DATA_MULTIPLE_VALUES_ASC
+ else:
+ assert products == list(reversed(EXPECTED_SORTED_DATA_MULTIPLE_VALUES_ASC))
+
+
+def test_sort_product_not_having_attribute_data(api_client, category, count_queries):
+ """Test the case where a product has a given attribute assigned to their
+ product type but no attribute data assigned, i.e. the product's PT was changed
+ after the product creation.
+ """
+ expected_results = ["Z", "Y", "A"]
+ product_create_kwargs = {
+ "category": category,
+ "price": zero_money(),
+ "is_published": True,
+ }
+
+ # Create two product types, with one forced to be at the bottom (no such attribute)
+ product_type = product_models.ProductType.objects.create(name="Apples")
+ other_product_type = product_models.ProductType.objects.create(name="Chocolates")
+
+ # Assign an attribute to the product type
+ attribute = product_models.Attribute.objects.create(name="Kind", slug="kind")
+ value = product_models.AttributeValue.objects.create(
+ name="Value", slug="value", attribute=attribute
+ )
+ product_type.product_attributes.add(attribute)
+
+ # Create a product with a value
+ product_having_attr_value = product_models.Product.objects.create(
+ name="Z", product_type=product_type, **product_create_kwargs
+ )
+ associate_attribute_values_to_instance(product_having_attr_value, attribute, value)
+
+ # Create a product having the same product type but no attribute data
+ product_models.Product.objects.create(
+ name="Y", product_type=product_type, **product_create_kwargs
+ )
+
+ # Create a new product having a name that would be ordered first in ascending
+ # as the default ordering is by name for non matching products
+ product_models.Product.objects.create(
+ name="A", product_type=other_product_type, **product_create_kwargs
+ )
+
+ # Sort the products
+ qs = product_models.Product.objects.sort_by_attribute(attribute_pk=attribute.pk)
+ qs = qs.values_list("name", flat=True)
+
+ # Compare the results
+ sorted_results = list(qs)
+ assert sorted_results == expected_results
diff --git a/tests/api/utils.py b/tests/api/utils.py
index dff86a18d4..129dbe32e8 100644
--- a/tests/api/utils.py
+++ b/tests/api/utils.py
@@ -10,13 +10,14 @@ def _get_graphql_content_from_response(response):
return json.loads(response.content.decode("utf8"))
-def get_graphql_content(response):
+def get_graphql_content(response, *, ignore_errors: bool = False):
"""Gets GraphQL content from the response, and optionally checks if it
contains any operating-related errors, eg. schema errors or lack of
permissions.
"""
content = _get_graphql_content_from_response(response)
- assert "errors" not in content, content["errors"]
+ if not ignore_errors:
+ assert "errors" not in content, content["errors"]
return content