Skip to content

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

Add custom sort by

fowczarekc4400805c343
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 078ede7393..e34ea88e3e 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -27,6 +27,7 @@ from .filters import (
filter_products_by_stock_availability,
sort_qs,
)
+from .sorters import CollectionSortEnum
if TYPE_CHECKING:
from ..product.types import ProductOrder # noqa
@@ -85,7 +86,7 @@ def resolve_collections(info, query, sort_by=None, **_kwargs):
user = info.context.user
qs = models.Collection.objects.visible_to_user(user)
qs = filter_by_query_param(qs, query, COLLECTION_SEARCH_FIELDS)
- qs = sort_queryset(qs, sort_by)
+ qs = sort_queryset(qs, sort_by, CollectionSortEnum)
return gql_optimizer.query(qs, info)
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index 8d42905e6b..3c92e8e7c5 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -1,4 +1,5 @@
import graphene
+from django.db.models import Count, QuerySet
from ..core.types import SortInputObjectType
@@ -6,21 +7,26 @@ from ..core.types import SortInputObjectType
class CollectionSortEnum(graphene.Enum):
NAME = "name"
AVAILABILITY = "is_published"
- # TODO: Add sorting by product count
- # PRODUCT_COUNT = "collectionproduct"
+ PRODUCT_COUNT = "product_count"
@property
def description(self):
+ # pylint: disable=no-member
if self in [
CollectionSortEnum.NAME,
CollectionSortEnum.AVAILABILITY,
- # CollectionSortEnum.PRODUCT_COUNT,
+ CollectionSortEnum.PRODUCT_COUNT,
]:
sort_name = self.name.lower().replace("_", " ")
return f"Sort collections by {sort_name}."
- # pylint: disable=no-member
raise ValueError("Unsupported enum value: %s" % self.value)
+ @staticmethod
+ def sort_by_product_count(queryset: QuerySet, sort_by: dict):
+ return queryset.annotate(product_count=Count("collectionproduct__id")).order_by(
+ f"{sort_by.direction}product_count", "slug"
+ )
+
class CollectionSortInput(SortInputObjectType):
class Meta:
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a3a491a3b3..0cd564dfbe 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -953,6 +953,7 @@ type CollectionReorderProducts {
enum CollectionSortEnum {
NAME
AVAILABILITY
+ PRODUCT_COUNT
}
input CollectionSortInput {
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index 9e4c8aa54c..388a0da1a9 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -9,7 +9,7 @@ from graphql_jwt.utils import jwt_payload
from graphql_relay import from_global_id
from .core.enums import PermissionEnum, ReportingPeriod
-from .core.types import PermissionDisplay
+from .core.types import PermissionDisplay, SortInputObjectType
ERROR_COULD_NO_RESOLVE_GLOBAL_ID = (
"Could not resolve to a node with the global id list of '%s'."
@@ -123,7 +123,7 @@ def filter_by_query_param(queryset, query, search_fields):
return queryset
-def sort_queryset(queryset: QuerySet, sort_by: dict):
+def sort_queryset(queryset: QuerySet, sort_by: dict, sort_enum: SortInputObjectType):
"""Sort queryset according to given parameters.
Keyword Arguments:
@@ -137,7 +137,13 @@ def sort_queryset(queryset: QuerySet, sort_by: dict):
direction = sort_by.direction
sorting_field = sort_by.field
- queryset = queryset.order_by(f"{direction}{sorting_field}")
+ custom_sort_by_name = f"sort_by_{sorting_field}"
+
+ if custom_sort_by_name in dir(sort_enum):
+ custom_sort_by = getattr(sort_enum, custom_sort_by_name)
+ queryset = custom_sort_by(queryset, sort_by)
+ else:
+ queryset = queryset.order_by(f"{direction}{sorting_field}")
return queryset
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 452ded1514..3d09ef8d8d 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -2661,12 +2661,12 @@ QUERY_COLLECTIONS_WITH_SEARCH = """
({"field": "NAME", "direction": "DESC"}, ["Coll3", "Coll2", "Coll1"]),
({"field": "AVAILABILITY", "direction": "ASC"}, ["Coll2", "Coll1", "Coll3"]),
({"field": "AVAILABILITY", "direction": "DESC"}, ["Coll1", "Coll3", "Coll2"]),
- # ({"field": "PRODUCT_COUNT", "direction": "ASC"}),
- # ({"field": "PRODUCT_COUNT", "direction": "DESC"}),
+ ({"field": "PRODUCT_COUNT", "direction": "ASC"}, ["Coll3", "Coll1", "Coll2"]),
+ ({"field": "PRODUCT_COUNT", "direction": "DESC"}, ["Coll2", "Coll3", "Coll1"]),
],
)
def test_collections_query_with_search(
- collection_sort, result_order, staff_api_client, permission_manage_products
+ collection_sort, result_order, staff_api_client, permission_manage_products, product
):
Collection.objects.bulk_create(
[
@@ -2677,6 +2677,7 @@ def test_collections_query_with_search(
Collection(name="Coll3", slug="collection-published", is_published=True),
]
)
+ product.collections.add(Collection.objects.get(name="Coll2"))
variables = {"sort_by": collection_sort}
staff_api_client.user.user_permissions.add(permission_manage_products)