Skip to content

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

Add default sorting for search products

Damian W24907bc2d70a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3c8556d18e..5ff8870396 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -62,6 +62,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Prevent negative available quantity - #6897 by @d-wysocki
- Fix CheckoutLinesInfoByCheckoutTokenLoader dataloader - #6929 by @IKarbowiak
- Change the `app` query to return info about the currently authenticated app - #6928 by @d-wysocki
+- Add default sorting by rank for search products - #6936 by @d-wysocki
# 2.11.1
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index caf5ddc138..0c1da5e288 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -2509,6 +2509,49 @@ def test_search_product_by_description_and_name(
assert data[2]["node"]["name"] == product_1.name
+def test_search_product_by_description_and_name_without_sort_by(
+ user_api_client, product_list, product, channel_USD, category, product_type
+):
+ search_query = """
+ query Products(
+ $filters: ProductFilterInput, $sortBy: ProductOrder,$channel: String
+ ) {
+ products(first: 10, filter: $filters, sortBy: $sortBy,channel: $channel) {
+ edges {
+ node {
+ id
+ name
+ slug
+ }
+ }
+ }
+ }
+ """
+ product.description_plaintext = "red big red product"
+ product.save()
+
+ product_2 = product_list[1]
+ product_2.name = "red product"
+ product_2.save()
+ product_1 = product_list[0]
+ product_1.description_plaintext = "some red product"
+ product_1.save()
+
+ variables = {
+ "filters": {
+ "search": "red",
+ },
+ "channel": channel_USD.slug,
+ }
+ response = user_api_client.post_graphql(search_query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["products"]["edges"]
+
+ assert data[0]["node"]["name"] == product_2.name
+ assert data[1]["node"]["name"] == product.name
+ assert data[2]["node"]["name"] == product_1.name
+
+
@freeze_time("2020-03-18 12:00:00")
def test_create_product_with_rating(
staff_api_client,
diff --git a/saleor/graphql/utils/sorting.py b/saleor/graphql/utils/sorting.py
index 97ddfd2f09..5dda28ecae 100644
--- a/saleor/graphql/utils/sorting.py
+++ b/saleor/graphql/utils/sorting.py
@@ -24,8 +24,11 @@ def _sort_queryset_by_attribute(queryset, sorting_attribute, sorting_direction):
def sort_queryset_for_connection(iterable, args):
sort_by = args.get("sort_by")
reversed = True if "last" in args else False
+ query = getattr(iterable, "query", None)
if sort_by:
iterable = sort_queryset(queryset=iterable, sort_by=sort_by, reversed=reversed)
+ elif query and "-rank" in query.order_by:
+ return iterable, {"field": "rank", "direction": "-"}
else:
iterable, sort_by = sort_queryset_by_default(
queryset=iterable, reversed=reversed