Skip to content

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

No longer allow null values as sort_order

NyanKiyoshi4f22be6e815f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 379874ad97..9070cbc524 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ All notable, unreleased changes to this project will be documented in this file.
- The `SelectedAttribute` type now returns multiple values and will always return all the attributes assigned to the product type. - #4394 by @NyanKiyoshi
- Add attribute visibility config - #4449 by @dominik-zeglen
- Add slug generation = #4488 by @dominik-zeglen
+- Dropped `null` in `sort_order` fields to make it easier to reorder in API - #4481 by @NyanKiyoshi
## [Unreleased]
diff --git a/saleor/core/models.py b/saleor/core/models.py
index cb20d059ae..0e8ab7c2c7 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -8,7 +8,7 @@ from .utils.json_serializer import CustomJsonEncoder
class SortableModel(models.Model):
- sort_order = models.PositiveIntegerField(editable=False, db_index=True, null=True)
+ sort_order = models.PositiveIntegerField(editable=False, db_index=True, default=0)
class Meta:
abstract = True
@@ -22,7 +22,7 @@ class SortableModel(models.Model):
return existing_max
def save(self, *args, **kwargs):
- if self.sort_order is None:
+ if self.pk 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
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 6646262190..341154e24b 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -2,6 +2,7 @@ from typing import List
import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
+from django.db import transaction
from django.db.models import Q
from django.template.defaultfilters import slugify
@@ -362,11 +363,14 @@ class AttributeAssign(BaseMutation):
)
@classmethod
- def save_field_values(cls, product_type, field, pks):
+ def save_field_values(cls, product_type, model_name, pks):
"""Add in bulk the PKs to assign to a given product type."""
- getattr(product_type, field).add(*pks)
+ model = getattr(models, model_name)
+ for pk in pks:
+ model.objects.create(product_type=product_type, attribute_id=pk)
@classmethod
+ @transaction.atomic()
def perform_mutation(
cls, _root, info, product_type_id: str, operations: List[AttributeAssignInput]
):
@@ -387,8 +391,8 @@ class AttributeAssign(BaseMutation):
cls.clean_operations(product_type, product_attrs_pks, variant_attrs_pks)
# Commit
- cls.save_field_values(product_type, "product_attributes", product_attrs_pks)
- cls.save_field_values(product_type, "variant_attributes", variant_attrs_pks)
+ cls.save_field_values(product_type, "AttributeProduct", product_attrs_pks)
+ cls.save_field_values(product_type, "AttributeVariant", variant_attrs_pks)
return cls(product_type=product_type)
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 3df4dc93a4..6c6667f353 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -271,12 +271,17 @@ class CollectionAddProducts(BaseMutation):
permissions = ("product.manage_products",)
@classmethod
+ @transaction.atomic()
def perform_mutation(cls, _root, info, collection_id, products):
collection = cls.get_node_or_error(
info, collection_id, field="collection_id", only_type=Collection
)
products = cls.get_nodes_or_error(products, "products", Product)
- collection.products.add(*products)
+
+ for product in products:
+ models.CollectionProduct.objects.create(
+ collection=collection, product=product
+ )
return CollectionAddProducts(collection=collection)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index cebe575663..82eaa9835f 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -307,7 +307,7 @@ type AttributeUpdatePrivateMeta {
}
type AttributeValue implements Node {
- sortOrder: Int
+ sortOrder: Int!
id: ID!
name: String
slug: String
@@ -1608,7 +1608,7 @@ input MenuInput {
type MenuItem implements Node {
id: ID!
- sortOrder: Int
+ sortOrder: Int!
menu: Menu!
name: String!
parent: MenuItem
@@ -2522,7 +2522,7 @@ input ProductFilterInput {
}
type ProductImage implements Node {
- sortOrder: Int
+ sortOrder: Int!
id: ID!
alt: String!
url(size: Int): String!
diff --git a/saleor/menu/migrations/0015_remove_null_sort_order.py b/saleor/menu/migrations/0015_remove_null_sort_order.py
new file mode 100644
index 0000000000..fd86fe8331
--- /dev/null
+++ b/saleor/menu/migrations/0015_remove_null_sort_order.py
@@ -0,0 +1,33 @@
+# Generated by Django 2.2.3 on 2019-07-17 11:26
+
+from django.db import migrations, models
+from django.db.models import Max
+
+
+def set_default_position_menu_item(apps, schema_editor):
+ MenuItem = apps.get_model("menu", "MenuItem")
+
+ existing_max = MenuItem.objects.aggregate(Max("sort_order"))
+ existing_max = existing_max.get("sort_order__max") or 0
+
+ for sort_order, item in enumerate(
+ MenuItem.objects.filter(sort_order=None), existing_max + 1
+ ):
+ item.sort_order = sort_order
+ item.save(update_fields=["sort_order"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("menu", "0014_auto_20190523_0759")]
+
+ operations = [
+ migrations.RunPython(set_default_position_menu_item),
+ migrations.AlterField(
+ model_name="menuitem",
+ name="sort_order",
+ field=models.PositiveIntegerField(
+ db_index=True, default=0, editable=False, null=False
+ ),
+ ),
+ ]
diff --git a/saleor/product/migrations/0100_remove_null_sort_order.py b/saleor/product/migrations/0100_remove_null_sort_order.py
new file mode 100644
index 0000000000..9bbc65dcec
--- /dev/null
+++ b/saleor/product/migrations/0100_remove_null_sort_order.py
@@ -0,0 +1,89 @@
+# Generated by Django 2.2.3 on 2019-07-17 11:26
+
+from django.db import migrations, models
+from django.db.models import Max
+
+
+def _set_default_position(qs):
+ existing_max = qs.aggregate(Max("sort_order"))
+ existing_max = existing_max.get("sort_order__max") or 0
+
+ for sort_order, item in enumerate(qs.filter(sort_order=None), existing_max + 1):
+ item.sort_order = sort_order
+ item.save(update_fields=["sort_order"])
+
+
+def set_default_position_m2m(model_name, fk_name):
+ def _wrapped(apps, schema_editor):
+ attribute_m2m = apps.get_model("product", model_name)
+ foreigners = attribute_m2m.objects.distinct().values_list(fk_name, flat=True)
+
+ for pk in foreigners:
+ _set_default_position(attribute_m2m.objects.filter(**{fk_name: pk}))
+
+ return _wrapped
+
+
+def set_default_position_m2o(model_name):
+ def _wrapped(apps, schema_editor):
+ attribute_m2m = apps.get_model("product", model_name)
+ _set_default_position(attribute_m2m.objects)
+
+ return _wrapped
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("product", "0099_auto_20190626_0815")]
+
+ operations = [
+ # m2m models
+ migrations.RunPython(
+ set_default_position_m2m("AttributeProduct", "product_type_id")
+ ),
+ migrations.RunPython(
+ set_default_position_m2m("AttributeVariant", "product_type_id")
+ ),
+ migrations.RunPython(
+ set_default_position_m2m("CollectionProduct", "collection_id")
+ ),
+ # m2o models
+ migrations.RunPython(set_default_position_m2o("AttributeValue")),
+ migrations.RunPython(set_default_position_m2o("ProductImage")),
+ # drop nulls
+ migrations.AlterField(
+ model_name="attributeproduct",
+ name="sort_order",
+ field=models.PositiveIntegerField(
+ db_index=True, editable=False, default=0, null=False
+ ),
+ ),
+ migrations.AlterField(
+ model_name="attributevariant",
+ name="sort_order",
+ field=models.PositiveIntegerField(
+ db_index=True, editable=False, default=0, null=False
+ ),
+ ),
+ migrations.AlterField(
+ model_name="collectionproduct",
+ name="sort_order",
+ field=models.PositiveIntegerField(
+ db_index=True, editable=False, default=0, null=False
+ ),
+ ),
+ migrations.AlterField(
+ model_name="attributevalue",
+ name="sort_order",
+ field=models.PositiveIntegerField(
+ db_index=True, editable=False, default=0, null=False
+ ),
+ ),
+ migrations.AlterField(
+ model_name="productimage",
+ name="sort_order",
+ field=models.PositiveIntegerField(
+ db_index=True, editable=False, default=0, null=False
+ ),
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index b4e2f4f27a..cbf7f1fc87 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -7,7 +7,7 @@ from django.contrib.postgres.fields import JSONField
from django.core import exceptions
from django.core.validators import MinValueValidator
from django.db import models
-from django.db.models import F, Q
+from django.db.models import Q
from django.urls import reverse
from django.utils.encoding import smart_text
from django.utils.html import strip_tags
@@ -145,7 +145,7 @@ class ProductsQueryset(PublishedQuerySet):
qs = self.visible_to_user(user).prefetch_related(
"collections__products__collectionproduct"
)
- qs = qs.order_by(F("collectionproduct__sort_order").asc(nulls_last=True))
+ qs = qs.order_by("collectionproduct__sort_order")
return qs
@@ -503,14 +503,12 @@ class AttributeQuerySet(models.QuerySet):
return self.get_public_attributes()
def product_attributes_sorted_for_dashboard(self, asc=True):
- field = F("attributeproduct__sort_order")
- sort_meth = getattr(field, "asc" if asc else "desc")
- return self.order_by(sort_meth(nulls_last=True))
+ direction = "" if asc else "-"
+ return self.order_by(f"{direction}attributeproduct__sort_order")
def variant_attributes_sorted_for_dashboard(self, asc=True):
- field = F("attributevariant__sort_order")
- sort_meth = getattr(field, "asc" if asc else "desc")
- return self.order_by(sort_meth(nulls_last=True))
+ direction = "" if asc else "-"
+ return self.order_by(f"{direction}attributevariant__sort_order")
class Attribute(ModelWithMetadata):
diff --git a/tests/api/test_product_sorting.py b/tests/api/test_product_sorting.py
index 8d87c8d27b..a872a967a2 100644
--- a/tests/api/test_product_sorting.py
+++ b/tests/api/test_product_sorting.py
@@ -2,9 +2,8 @@ from typing import Dict, List
import graphene
import pytest
-from prices import Money
-from saleor.product.models import CollectionProduct, Product
+from saleor.product.models import Product
from tests.api.utils import get_graphql_content
GET_SORTED_PRODUCTS_COLLECTION_QUERY = """
@@ -127,7 +126,7 @@ def test_sort_products_within_collection(
product_move_2 = expected_product_order.pop(0)
expected_product_order.insert(2, product_move_2)
- expected_product_order.insert(0, product_move_1)
+ expected_product_order.insert(1, product_move_1)
moves = [
{
@@ -149,59 +148,3 @@ def test_sort_products_within_collection(
# Look if the order is right
_assert_product_are_correctly_ordered(expected_product_order, products)
-
-
-def test_sort_products_within_collection_null_sort_order_is_ordered_to_last(
- staff_api_client,
- staff_user,
- collection,
- category,
- product_type,
- permission_manage_products,
-):
- db_products = CollectionProduct.objects.bulk_create(
- [
- CollectionProduct(
- collection=collection,
- product=Product.objects.create(
- price=Money(10, "USD"), product_type=product_type, category=category
- ),
- ),
- CollectionProduct(
- collection=collection,
- sort_order=1,
- product=Product.objects.create(
- price=Money(10, "USD"), product_type=product_type, category=category
- ),
- ),
- ]
- )
-
- assert db_products[0].sort_order is None
- assert db_products[1].sort_order == 1
-
- staff_api_client.user.user_permissions.add(permission_manage_products)
- null_product_id = graphene.Node.to_global_id("Product", db_products[0].product.pk)
-
- collection_id = graphene.Node.to_global_id("Collection", collection.pk)
- products = get_graphql_content(
- staff_api_client.post_graphql(
- GET_SORTED_PRODUCTS_COLLECTION_QUERY, {"id": collection_id}
- )
- )["data"]["collection"]["products"]["edges"]
-
- assert len(products) == len(db_products)
- assert products[-1]["node"]["id"] == null_product_id
-
- products = get_graphql_content(
- staff_api_client.post_graphql(
- COLLECTION_RESORT_QUERY,
- {
- "collectionId": collection_id,
- "moves": [{"productId": null_product_id, "sortOrder": -len(products)}],
- },
- )
- )["data"]["collectionReorderProducts"]["collection"]["products"]["edges"]
-
- # Ensure it was properly pushed to the top
- assert products[0]["node"]["id"] == null_product_id
diff --git a/tests/test_core.py b/tests/test_core.py
index 818a232eda..1c6ac4462f 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -311,12 +311,6 @@ def test_build_absolute_uri(site_settings, settings):
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()
-
-
def test_csrf_middleware_is_enabled():
csrf_client = Client(enforce_csrf_checks=True)
checkout_url = reverse("checkout:index")