Skip to content

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

Remove unused code due to refactoring and make sort_order null by design

NyanKiyoshica6fddbe5bf3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4ac025b6e6..c9802d14c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Rename menu items in Dashboard 2.0 - #4172 by @benekex2
- Adding a non existent variant to a checkout no longer crashes - #4166 by @NyanKiyoshi
- Category delete modal improvements - #4171 by @benekex2
+- Products are now sortable within collections - #4123 by @NyanKiyoshi
## 2.6.0
diff --git a/saleor/core/models.py b/saleor/core/models.py
index c499e21bb5..2494d61125 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -4,62 +4,33 @@ from django.db import models
from django.db.models import F, Max, Q
-class _BaseSortableModel(models.Model):
+class SortableModel(models.Model):
+ sort_order = models.PositiveIntegerField(editable=False, db_index=True, null=True)
+
class Meta:
abstract = True
def get_ordering_queryset(self):
raise NotImplementedError("Unknown ordering queryset")
- @property
- def _sort_order_field_name(self):
- return "sort_order"
-
- @property
- def _sort_order(self):
- return getattr(self, self._sort_order_field_name)
-
- @_sort_order.setter
- def _sort_order(self, value):
- setattr(self, self._sort_order_field_name, value)
-
- def _get_max_sort_order(self, qs):
- existing_max = qs.aggregate(Max(self._sort_order_field_name))
- existing_max = existing_max.get(f"{self._sort_order_field_name}__max")
+ def get_max_sort_order(self, qs):
+ existing_max = qs.aggregate(Max("sort_order"))
+ existing_max = existing_max.get("sort_order__max")
return existing_max
- def get_max_sort_order(self):
- return self._get_max_sort_order(self.get_ordering_queryset())
-
def save(self, *args, **kwargs):
- if self._sort_order is None:
+ if self.sort_order is None:
qs = self.get_ordering_queryset()
- existing_max = self._get_max_sort_order(qs)
- self._sort_order = 0 if existing_max is None else existing_max + 1
+ existing_max = self.get_max_sort_order(qs)
+ self.sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
qs = self.get_ordering_queryset()
- qs.filter(**{f"{self._sort_order_field_name}__gt": self._sort_order}).update(
- **{self._sort_order_field_name: F(self._sort_order_field_name) - 1}
- )
+ qs.filter(sort_order__gt=self.sort_order).update(sort_order=F("sort_order") - 1)
super().delete(*args, **kwargs)
-class SortableModel(_BaseSortableModel):
- sort_order = models.PositiveIntegerField(editable=False, db_index=True)
-
- class Meta:
- abstract = True
-
-
-class SortableModelNullable(_BaseSortableModel):
- sort_order = models.PositiveIntegerField(editable=False, db_index=True, null=True)
-
- class Meta:
- abstract = True
-
-
class PublishedQuerySet(models.QuerySet):
def published(self):
today = datetime.date.today()
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index e122b8ec2b..7ea5e27057 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -245,11 +245,12 @@ class CollectionReorderProducts(BaseMutation):
)
if current_rel_pos is None:
- # This case should never happen,
- # except when products were migrated from a previous version
- # or using unit-tests because of the usage of `bulk_create`
+ # This case happens when products created using a bulk_creation
+ # e.g., bulk_create or collections.add
if node.sort_order is None:
- current_rel_pos = node.get_max_sort_order() or 0
+ current_rel_pos = (
+ node.get_max_sort_order(node.get_ordering_queryset()) or 0
+ )
else:
current_rel_pos = node.sort_order
else:
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 71a98029c2..b9b9668308 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -166,7 +166,7 @@ input AttributeUpdateInput {
}
type AttributeValue implements Node {
- sortOrder: Int!
+ sortOrder: Int
id: ID!
name: String
slug: String
@@ -1316,7 +1316,7 @@ input MenuInput {
type MenuItem implements Node {
id: ID!
- sortOrder: Int!
+ sortOrder: Int
menu: Menu!
name: String!
parent: MenuItem
@@ -2130,7 +2130,7 @@ input ProductFilterInput {
}
type ProductImage implements Node {
- sortOrder: Int!
+ sortOrder: Int
id: ID!
alt: String!
url(size: Int): String!
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index af5e5c164f..b9d78d9dfb 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -62,7 +62,7 @@ def _resolve_graphene_type(type_name):
raise AssertionError("Could not resolve the type {}".format(type_name))
-def get_nodes(ids, graphene_type=None, qs=None):
+def get_nodes(ids, graphene_type=None):
"""Return a list of nodes.
If the `graphene_type` argument is provided, the IDs will be validated
@@ -78,10 +78,7 @@ def get_nodes(ids, graphene_type=None, qs=None):
if nodes_type and not graphene_type:
graphene_type = _resolve_graphene_type(nodes_type)
- if qs is None:
- qs = graphene_type._meta.model.objects
-
- nodes = list(qs.filter(pk__in=pks))
+ nodes = list(graphene_type._meta.model.objects.filter(pk__in=pks))
nodes.sort(key=lambda e: pks.index(str(e.pk))) # preserve order in pks
if not nodes:
diff --git a/saleor/menu/migrations/0014_auto_20190523_0759.py b/saleor/menu/migrations/0014_auto_20190523_0759.py
new file mode 100644
index 0000000000..6e167c9283
--- /dev/null
+++ b/saleor/menu/migrations/0014_auto_20190523_0759.py
@@ -0,0 +1,16 @@
+# Generated by Django 2.2.1 on 2019-05-23 12:59
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("menu", "0013_auto_20190507_0309")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="menuitem",
+ name="sort_order",
+ field=models.PositiveIntegerField(db_index=True, editable=False, null=True),
+ )
+ ]
diff --git a/saleor/menu/models.py b/saleor/menu/models.py
index 878aff7b1f..3b1a2763bb 100644
--- a/saleor/menu/models.py
+++ b/saleor/menu/models.py
@@ -27,11 +27,7 @@ class Menu(models.Model):
return self.name
-class _MenuItemMeta(type(MPTTModel), type(SortableModel)):
- pass
-
-
-class MenuItem(MPTTModel, SortableModel, metaclass=_MenuItemMeta):
+class MenuItem(MPTTModel, SortableModel):
menu = models.ForeignKey(Menu, related_name="items", on_delete=models.CASCADE)
name = models.CharField(max_length=128)
parent = models.ForeignKey(
diff --git a/saleor/product/migrations/0093_auto_20190521_0124.py b/saleor/product/migrations/0093_auto_20190521_0124.py
index 3b7fd08862..43932f48bf 100644
--- a/saleor/product/migrations/0093_auto_20190521_0124.py
+++ b/saleor/product/migrations/0093_auto_20190521_0124.py
@@ -32,4 +32,14 @@ class Migration(migrations.Migration):
),
),
migrations.AlterModelTable(name="collectionproduct", table=None),
+ migrations.AlterField(
+ model_name="attributevalue",
+ name="sort_order",
+ field=models.PositiveIntegerField(db_index=True, editable=False, null=True),
+ ),
+ migrations.AlterField(
+ model_name="productimage",
+ name="sort_order",
+ field=models.PositiveIntegerField(db_index=True, editable=False, null=True),
+ ),
]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 37716f70d3..9b694d0c30 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -23,7 +23,7 @@ from saleor.core.utils import build_absolute_uri
from ..core import TaxRateType
from ..core.exceptions import InsufficientStock
-from ..core.models import PublishableModel, SortableModel, SortableModelNullable
+from ..core.models import PublishableModel, SortableModel
from ..core.utils.taxes import apply_tax_to_price
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
@@ -192,9 +192,6 @@ class Product(SeoModel, PublishableModel):
price = apply_tax_to_price(taxes, tax_rate, price)
return TaxedMoneyRange(start=price, stop=price)
- def get_ordering_queryset(self):
- return self.category.products.all()
-
class ProductTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)
@@ -536,7 +533,7 @@ class VariantImage(models.Model):
)
-class CollectionProduct(SortableModelNullable):
+class CollectionProduct(SortableModel):
collection = models.ForeignKey(
"Collection", related_name="collectionproduct", on_delete=models.CASCADE
)
diff --git a/tests/api/test_product_sorting.py b/tests/api/test_product_sorting.py
index 0e5c5ecc1e..9cb239f690 100644
--- a/tests/api/test_product_sorting.py
+++ b/tests/api/test_product_sorting.py
@@ -51,7 +51,7 @@ def _assert_product_are_correctly_ordered(expected: List[Product], nodes: List[D
@pytest.mark.parametrize("wanted_pos, expected_pos", ((-100, 0), (+100, 100)))
-def test_sort_products_within_category_with_out_of_bound_value(
+def test_sort_products_within_collection_with_out_of_bound_value(
staff_api_client,
collection,
product,
@@ -81,6 +81,27 @@ def test_sort_products_within_category_with_out_of_bound_value(
assert product.collectionproduct.first().sort_order == expected_pos
+def test_sort_products_within_collection_invalid_id(
+ staff_api_client, collection, product, permission_manage_products
+):
+ product_id = graphene.Node.to_global_id("Collection", product.pk)
+ moves = [{"productId": product_id, "sortOrder": 1}]
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ COLLECTION_RESORT_QUERY,
+ {
+ "collectionId": graphene.Node.to_global_id("Collection", collection.pk),
+ "moves": moves,
+ },
+ permissions=[permission_manage_products],
+ )
+ )["data"]["collectionReorderProducts"]
+
+ assert content["errors"] == [
+ {"field": "moves", "message": f"Couldn't resolve to a node: {product_id}"}
+ ]
+
+
def test_sort_products_within_collection(
staff_api_client,
staff_user,
diff --git a/tests/test_core.py b/tests/test_core.py
index 1b2f92c8f3..c98638a880 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -277,3 +277,9 @@ def test_build_absolute_uri(site_settings, settings):
current_url = "%s://%s" % (protocol, site_settings.site.domain)
logo_location = urljoin(current_url, static("images/logo-light.svg"))
assert logo_url == logo_location
+
+
+def test_delete_sort_order_with_null_value(menu_item):
+ menu_item.sort_order = None
+ menu_item.save(update_fields=["sort_order"])
+ menu_item.delete()