Skip to content

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

Add numeric field to AttributeValue (#17982)

Maciej Korycinski56dfa35a662f
diff --git a/saleor/attribute/lock_objects.py b/saleor/attribute/lock_objects.py
new file mode 100644
index 0000000000..bf5cd4aa6e
--- /dev/null
+++ b/saleor/attribute/lock_objects.py
@@ -0,0 +1,9 @@
+from django.db.models import QuerySet
+
+from .models.base import AttributeValue
+
+
+def attribute_value_qs_select_for_update() -> QuerySet[AttributeValue]:
+ return AttributeValue.objects.order_by("sort_order", "pk").select_for_update(
+ of=(["self"])
+ )
diff --git a/saleor/attribute/migrations/0051_attributevalue_numeric.py b/saleor/attribute/migrations/0051_attributevalue_numeric.py
new file mode 100644
index 0000000000..1c2f12a26f
--- /dev/null
+++ b/saleor/attribute/migrations/0051_attributevalue_numeric.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.1 on 2025-07-17 10:56
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("attribute", "0050_alter_attribute_input_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attributevalue",
+ name="numeric",
+ field=models.FloatField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/attribute/migrations/0052_attributevalue_attribute_value_numeric_idx.py b/saleor/attribute/migrations/0052_attributevalue_attribute_value_numeric_idx.py
new file mode 100644
index 0000000000..49aad5d733
--- /dev/null
+++ b/saleor/attribute/migrations/0052_attributevalue_attribute_value_numeric_idx.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.1 on 2025-07-17 11:03
+
+import django.contrib.postgres.indexes
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("attribute", "0051_attributevalue_numeric"),
+ ("page", "0031_alter_page_metadata_alter_page_private_metadata_and_more"),
+ ("product", "0201_productvariant_variant_gin"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="attributevalue",
+ index=django.contrib.postgres.indexes.BTreeIndex(
+ fields=["numeric"], name="attribute_value_numeric_idx"
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/migrations/0053_fulfill_numeric_attribute_value.py b/saleor/attribute/migrations/0053_fulfill_numeric_attribute_value.py
new file mode 100644
index 0000000000..0de1a8701a
--- /dev/null
+++ b/saleor/attribute/migrations/0053_fulfill_numeric_attribute_value.py
@@ -0,0 +1,28 @@
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from .tasks.saleor3_22 import fulfill_attribute_value_numeric_field
+
+
+def set_up_numeric_attribute_values(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ fulfill_attribute_value_numeric_field.delay()
+
+ sender = registry.get_app_config("attribute")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("attribute", "0052_attributevalue_attribute_value_numeric_idx"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ set_up_numeric_attribute_values,
+ reverse_code=migrations.RunPython.noop,
+ )
+ ]
diff --git a/saleor/attribute/migrations/tasks/__init__.py b/saleor/attribute/migrations/tasks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/attribute/migrations/tasks/saleor3_22.py b/saleor/attribute/migrations/tasks/saleor3_22.py
new file mode 100644
index 0000000000..27e1797aee
--- /dev/null
+++ b/saleor/attribute/migrations/tasks/saleor3_22.py
@@ -0,0 +1,40 @@
+from django.db import transaction
+from django.db.models import F, FloatField
+from django.db.models.functions import Cast
+
+from ....celeryconf import app
+from ....core.db.connection import allow_writer
+from ...models.base import AttributeValue
+
+# Takes around 0.11 seconds to process the batch.
+# The memory usage is marginal (~1MB).
+BATCH_SIZE = 500
+
+
+@allow_writer()
+def fulfill_attribute_value_numeric_field(attribute_value_pk=0):
+ value_ids = list(
+ AttributeValue.objects.filter(
+ pk__gte=attribute_value_pk,
+ numeric__isnull=True,
+ attribute__input_type="numeric",
+ )
+ .order_by("pk")
+ .values_list("id", flat=True)[:BATCH_SIZE]
+ )
+
+ if not value_ids:
+ return
+
+ with transaction.atomic():
+ locked_values = (
+ AttributeValue.objects.filter(id__in=value_ids)
+ .order_by("sort_order", "pk")
+ .select_for_update()
+ .values_list("id", flat=True)
+ )
+ AttributeValue.objects.filter(id__in=locked_values).update(
+ numeric=Cast(F("name"), FloatField())
+ )
+ fulfill_attribute_value_numeric_field.delay(value_ids[-1])
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 574b5ece25..892f07af71 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -1,6 +1,6 @@
from typing import TYPE_CHECKING, TypeVar, Union
-from django.contrib.postgres.indexes import GinIndex
+from django.contrib.postgres.indexes import BTreeIndex, GinIndex
from django.db import models, transaction
from django.db.models import Case, Exists, F, OrderBy, OuterRef, Q, Value, When
@@ -319,10 +319,18 @@ class AttributeValueManager(models.Manager):
)
if objects_to_be_updated:
- self.bulk_update(
- objects_to_be_updated,
- fields=update_fields,
- )
+ from ..lock_objects import attribute_value_qs_select_for_update
+
+ with transaction.atomic():
+ _locked_qs = (
+ attribute_value_qs_select_for_update()
+ .filter(pk__in=[obj.pk for obj in objects_to_be_updated])
+ .select_for_update(of=(["self"]))
+ )
+ self.bulk_update(
+ objects_to_be_updated,
+ fields=update_fields,
+ )
return results
@@ -355,6 +363,7 @@ class AttributeValue(ModelWithExternalReference):
)
boolean = models.BooleanField(blank=True, null=True)
date_time = models.DateTimeField(blank=True, null=True)
+ numeric = models.FloatField(null=True, blank=True)
reference_product = models.ForeignKey(
Product,
@@ -405,7 +414,11 @@ class AttributeValue(ModelWithExternalReference):
# `opclasses` and `fields` should be the same length
fields=["name", "slug"],
opclasses=["gin_trgm_ops"] * 2,
- )
+ ),
+ BTreeIndex(
+ fields=["numeric"],
+ name="attribute_value_numeric_idx",
+ ),
]
def __str__(self) -> str:
diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.py
index 05c96d76a8..b7e01c5059 100644
--- a/saleor/attribute/tests/fixtures/attribute.py
+++ b/saleor/attribute/tests/fixtures/attribute.py
@@ -487,8 +487,12 @@ def numeric_attribute(db):
filterable_in_dashboard=True,
available_in_grid=True,
)
- AttributeValue.objects.create(attribute=attribute, name="9.5", slug="10_5")
- AttributeValue.objects.create(attribute=attribute, name="15.2", slug="15_2")
+ AttributeValue.objects.create(
+ attribute=attribute, name="9.5", slug="10_5", numeric=9.5
+ )
+ AttributeValue.objects.create(
+ attribute=attribute, name="15.2", slug="15_2", numeric=15.2
+ )
return attribute
@@ -503,8 +507,8 @@ def numeric_attribute_without_unit(db):
filterable_in_dashboard=True,
available_in_grid=True,
)
- AttributeValue.objects.create(attribute=attribute, name="9", slug="9")
- AttributeValue.objects.create(attribute=attribute, name="15", slug="15")
+ AttributeValue.objects.create(attribute=attribute, name="9", slug="9", numeric=9)
+ AttributeValue.objects.create(attribute=attribute, name="15", slug="15", numeric=15)
return attribute
diff --git a/saleor/celeryconf.py b/saleor/celeryconf.py
index c4b6655815..0384cc64c6 100644
--- a/saleor/celeryconf.py
+++ b/saleor/celeryconf.py
@@ -37,6 +37,7 @@ app.autodiscover_tasks(
packages=[
"saleor.order.migrations.tasks",
"saleor.account.migrations.tasks",
+ "saleor.attribute.migrations.tasks",
],
related_name="saleor3_22",
)
diff --git a/saleor/graphql/attribute/bulk_mutations.py b/saleor/graphql/attribute/bulk_mutations.py
index e729438c25..4f788ff2e7 100644
--- a/saleor/graphql/attribute/bulk_mutations.py
+++ b/saleor/graphql/attribute/bulk_mutations.py
@@ -1,7 +1,9 @@
import graphene
+from django.db import transaction
from django.db.models import Exists, OuterRef, Q
from ...attribute import models
+from ...attribute.lock_objects import attribute_value_qs_select_for_update
from ...permission.enums import PageTypePermissions
from ...product import models as product_models
from ...webhook.event_types import WebhookEventAsyncType
@@ -126,8 +128,12 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):
@classmethod
def bulk_action(cls, info: ResolveInfo, queryset, /):
attributes = {value.attribute for value in queryset}
- values = list(queryset)
- queryset.delete()
+ with transaction.atomic():
+ locked_qs = attribute_value_qs_select_for_update()
+ locked_qs = locked_qs.filter(pk__in=queryset.values_list("pk", flat=True))
+ values = list(locked_qs)
+ queryset.delete()
+
manager = get_plugin_manager_promise(info.context).get()
webhooks = get_webhooks_for_event(WebhookEventAsyncType.ATTRIBUTE_VALUE_DELETED)
for value in values:
diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_update.py b/saleor/graphql/attribute/mutations/attribute_bulk_update.py
index a92338f23b..e5f5b7c84c 100644
--- a/saleor/graphql/attribute/mutations/attribute_bulk_update.py
+++ b/saleor/graphql/attribute/mutations/attribute_bulk_update.py
@@ -2,6 +2,7 @@ from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models import Q
from django.utils.text import slugify
from graphene.utils.str_converters import to_camel_case
@@ -10,6 +11,7 @@ from text_unidecode import unidecode
from ....attribute import models
from ....attribute.error_codes import AttributeBulkUpdateErrorCode
+from ....attribute.lock_objects import attribute_value_qs_select_for_update
from ....core.tracing import traced_atomic_transaction
from ....permission.enums import PageTypePermissions, ProductTypePermissions
from ....webhook.utils import get_webhooks_for_event
@@ -572,24 +574,28 @@ class AttributeBulkUpdate(BaseMutation):
values_to_remove.extend(attribute_data["remove_values"])
values_to_create.extend(attribute_data["add_values"])
- models.Attribute.objects.bulk_update(
- attributes_to_update,
- [
- "name",
- "slug",
- "unit",
- "value_required",
- "visible_in_storefront",
- "is_variant_only",
- "filterable_in_dashboard",
- "external_reference",
- ],
- )
+ with transaction.atomic():
+ models.Attribute.objects.bulk_update(
+ attributes_to_update,
+ [
+ "name",
+ "slug",
+ "unit",
+ "value_required",
+ "visible_in_storefront",
+ "is_variant_only",
+ "filterable_in_dashboard",
+ "external_reference",
+ ],
+ )
+ locked_ids = (
+ attribute_value_qs_select_for_update()
+ .filter(pk__in=[value.pk for value in values_to_remove])
+ .values_list("pk", flat=True)
+ )
+ models.AttributeValue.objects.filter(id__in=locked_ids).delete()
- models.AttributeValue.objects.filter(
- id__in=[values_to_remove.id for values_to_remove in values_to_remove]
- ).delete()
- models.AttributeValue.objects.bulk_create(values_to_create)
+ models.AttributeValue.objects.bulk_create(values_to_create)
updated_attributes.extend(attributes_to_update)
return updated_attributes, values_to_remove, values_to_create
diff --git a/saleor/graphql/attribute/mutations/attribute_delete.py b/saleor/graphql/attribute/mutations/attribute_delete.py
index 6d52623b7e..881af1cb73 100644
--- a/saleor/graphql/attribute/mutations/attribute_delete.py
+++ b/saleor/graphql/attribute/mutations/attribute_delete.py
@@ -1,6 +1,8 @@
import graphene
+from django.db import transaction
from ....attribute import models as models
+from ....attribute.lock_objects import attribute_value_qs_select_for_update
from ....permission.enums import ProductTypePermissions
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
@@ -44,3 +46,26 @@ class AttributeDelete(ModelDeleteMutation, ModelWithExtRefMutation):
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.attribute_deleted, instance)
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, external_reference=None, id=None
+ ):
+ """Perform a mutation that deletes a model instance."""
+ instance = cls.get_instance(info, external_reference=external_reference, id=id)
+
+ cls.clean_instance(info, instance)
+ db_id = instance.id
+ with transaction.atomic():
+ # Lock the attribute values to prevent concurrent modifications
+ locked_qs = attribute_value_qs_select_for_update().filter(
+ attribute_id=instance.id
+ )
+ models.AttributeValue.objects.filter(id__in=locked_qs).delete()
+ instance.delete()
+
+ # After the instance is deleted, set its ID to the original database's
+ # ID so that the success response contains ID of the deleted object.
+ instance.id = db_id
+ cls.post_save_action(info, instance, None)
+ return cls.success_response(instance)
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
index cf11f723e3..67bc7f7152 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
@@ -813,9 +813,15 @@ def test_attributes_values_with_limit(
AttributeValue.objects.bulk_create(
[
- AttributeValue(slug="10", name="num-10", attribute=numeric_attribute),
- AttributeValue(slug="20", name="num-20", attribute=numeric_attribute),
- AttributeValue(slug="30", name="num-30", attribute=numeric_attribute),
+ AttributeValue(
+ slug="10", name="10", numeric=10, attribute=numeric_attribute
+ ),
+ AttributeValue(
+ slug="20", name="20", numeric=20, attribute=numeric_attribute
+ ),
+ AttributeValue(
+ slug="30", name="30", numeric=30, attribute=numeric_attribute
+ ),
]
)
limit = 1
@@ -837,9 +843,15 @@ def test_attributes_values_default_limit(
# given
AttributeValue.objects.bulk_create(
[
- AttributeValue(slug="10", name="num-10", attribute=numeric_attribute),
- AttributeValue(slug="20", name="num-20", attribute=numeric_attribute),
- AttributeValue(slug="30", name="num-30", attribute=numeric_attribute),
+ AttributeValue(
+ slug="10", name="10", numeric=10, attribute=numeric_attribute
+ ),
+ AttributeValue(
+ slug="20", name="20", numeric=20, attribute=numeric_attribute
+ ),
+ AttributeValue(
+ slug="30", name="30", numeric=30, attribute=numeric_attribute
+ ),
]
)
attribute_count = {
diff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.py
index af2a347133..3f79359b0c 100644
--- a/saleor/graphql/attribute/utils/type_handlers.py
+++ b/saleor/graphql/attribute/utils/type_handlers.py
@@ -562,6 +562,7 @@ class NumericAttributeHandler(AttributeTypeHandler):
return []
defaults = {
"name": numeric_val,
+ "numeric": float(numeric_val),
}
return self._update_or_create_value(instance, defaults)
@@ -674,6 +675,7 @@ class LegacyValuesHandler(AttributeTypeHandler):
value = self.values_input.values[0]
defaults = {
"name": value,
+ "numeric": float(value),
}
return self._update_or_create_value(instance, defaults)
diff --git a/saleor/graphql/page/bulk_mutations.py b/saleor/graphql/page/bulk_mutations.py
index 193eb25baa..7775202548 100644
--- a/saleor/graphql/page/bulk_mutations.py
+++ b/saleor/graphql/page/bulk_mutations.py
@@ -1,9 +1,11 @@
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models.expressions import Exists, OuterRef
from ...attribute import AttributeInputType
from ...attribute import models as attribute_models
+from ...attribute.lock_objects import attribute_value_qs_select_for_update
from ...core.tracing import traced_atomic_transaction
from ...page import models
from ...permission.enums import PagePermissions, PageTypePermissions
@@ -51,10 +53,18 @@ class PageBulkDelete(ModelBulkDeleteMutation):
input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES
)
- attribute_models.AttributeValue.objects.filter(
- Exists(assigned_values.filter(value_id=OuterRef("id"))),
- Exists(attributes.filter(id=OuterRef("attribute_id"))),
- ).delete()
+ with transaction.atomic():
+ locked_ids = (
+ attribute_value_qs_select_for_update()
+ .filter(
+ Exists(assigned_values.filter(value_id=OuterRef("id"))),
+ Exists(attributes.filter(id=OuterRef("attribute_id"))),
+ )
+ .values_list("id", flat=True)
+ )
+ attribute_models.AttributeValue.objects.filter(
+ id__in=locked_ids,
+ ).delete()
class PageBulkPublish(BaseBulkMutation):
@@ -127,7 +137,15 @@ class PageTypeBulkDelete(ModelBulkDeleteMutation):
input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES
)
- attribute_models.AttributeValue.objects.filter(
- Exists(assigned_values.filter(value_id=OuterRef("id"))),
- Exists(attributes.filter(id=OuterRef("attribute_id"))),
- ).delete()
+ with transaction.atomic():
+ locked_ids = (
+ attribute_value_qs_select_for_update()
+ .filter(
+ Exists(assigned_values.filter(value_id=OuterRef("id"))),
+ Exists(attributes.filter(id=OuterRef("attribute_id"))),
+ )
+ .values_list("id", flat=True)
+ )
+ attribute_models.AttributeValue.objects.filter(
+ id__in=locked_ids,
+ ).delete()
diff --git a/saleor/graphql/page/filters.py b/saleor/graphql/page/filters.py
index 516e7bd582..b0169caf3a 100644
--- a/saleor/graphql/page/filters.py
+++ b/saleor/graphql/page/filters.py
@@ -2,8 +2,7 @@ from typing import Literal
import django_filters
import graphene
-from django.db.models import Exists, FloatField, OuterRef, Q
-from django.db.models.functions import Cast
+from django.db.models import Exists, OuterRef, Q
from graphql import GraphQLError
from ...attribute import AttributeInputType
@@ -99,12 +98,11 @@ def filter_by_slug_or_name(attr_id, attr_value, db_connection_name: str):
def filter_by_numeric_attribute(attr_id, numeric_value, db_connection_name: str):
qs_by_numeric = AttributeValue.objects.using(db_connection_name).filter(
- attribute_id=attr_id
+ attribute_id=attr_id, numeric__isnull=False
)
- qs_by_numeric = qs_by_numeric.annotate(numeric_value=Cast("name", FloatField()))
qs_by_numeric = filter_where_by_numeric_field(
qs_by_numeric,
- "numeric_value",
+ "numeric",
numeric_value,
)
assigned_attr_value = AssignedPageAttributeValue.objects.using(
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index dc2033c52b..17dc18f725 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -13,6 +13,7 @@ from .....page.error_codes import PageErrorCode
from .....page.models import Page, PageType
from .....tests.utils import dummy_editorjs
from .....webhook.event_types import WebhookEventAsyncType
+from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
CREATE_PAGE_MUTATION = """
@@ -60,13 +61,18 @@ CREATE_PAGE_MUTATION = """
@freeze_time("2020-03-18 12:00:00")
-def test_page_create_mutation(staff_api_client, permission_manage_pages, page_type):
+def test_page_create_mutation(
+ staff_api_client, permission_manage_pages, page_type, numeric_attribute
+):
+ # given
page_slug = "test-slug"
page_content = dummy_editorjs("test content", True)
page_title = "test title"
page_is_published = True
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+ page_type.page_attributes.add(numeric_attribute)
+
# Default attributes defined in page_type fixture
tag_attr = page_type.page_attributes.get(name="tag")
tag_value_slug = tag_attr.values.first().slug
@@ -78,6 +84,9 @@ def test_page_create_mutation(staff_api_client, permission_manage_pages, page_ty
size_attr_id = graphene.Node.to_global_id("Attribute", size_attr.id)
non_existent_attr_value = "New value"
+ numeric_value = 42.1
+ numeric_name = str(numeric_value)
+
# test creating root page
variables = {
"input": {
@@ -89,13 +98,20 @@ def test_page_create_mutation(staff_api_client, permission_manage_pages, page_ty
"attributes": [
{"id": tag_attr_id, "values": [tag_value_name]},
{"id": size_attr_id, "values": [non_existent_attr_value]},
+ {
+ "id": to_global_id_or_none(numeric_attribute),
+ "values": [numeric_name],
+ },
],
}
}
+ # when
response = staff_api_client.post_graphql(
CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["pageCreate"]
assert data["errors"] == []
@@ -114,6 +130,9 @@ def test_page_create_mutation(staff_api_client, permission_manage_pages, page_ty
)
assert slugify(non_existent_attr_value) in values
assert tag_value_slug in values
+ assert numeric_attribute.values.filter(
+ name=numeric_name, numeric=numeric_value
+ ).exists()
@freeze_time("2020-03-18 12:00:00")
@@ -1497,3 +1516,61 @@ def test_create_page_with_single_reference_attributes(
]
for attr_data in attributes_data:
assert attr_data in expected_attributes_data
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_page_create_mutation_with_numeric_attribue(
+ staff_api_client, permission_manage_pages, page_type, numeric_attribute
+):
+ # given
+ page_slug = "test-slug"
+ page_content = dummy_editorjs("test content", True)
+ page_title = "test title"
+ page_is_published = True
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+ page_type.page_attributes.all().delete()
+ page_type.page_attributes.add(numeric_attribute)
+
+ numeric_value = 42.1
+ numeric_name = str(numeric_value)
+
+ # test creating root page
+ variables = {
+ "input": {
+ "title": page_title,
+ "content": page_content,
+ "isPublished": page_is_published,
+ "slug": page_slug,
+ "pageType": page_type_id,
+ "attributes": [
+ {
+ "id": to_global_id_or_none(numeric_attribute),
+ "numeric": numeric_name,
+ },
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageCreate"]
+ assert data["errors"] == []
+
+ assert len(data["page"]["attributes"]) == 1
+ attribute = data["page"]["attributes"][0]
+ assert attribute["attribute"]["slug"] == numeric_attribute.slug
+ assert len(attribute["values"]) == 1
+ assert (
+ attribute["values"][0]["slug"]
+ == f"{Page.objects.get().id}_{numeric_attribute.id}"
+ )
+ assert attribute["values"][0]["name"] == numeric_name
+
+ assert numeric_attribute.values.filter(
+ name=numeric_name, numeric=numeric_value
+ ).exists()
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index 896e0d50f9..f2e595f3c2 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -21,6 +21,7 @@ from .....page.error_codes import PageErrorCode
from .....page.models import Page
from .....tests.utils import dummy_editorjs
from .....webhook.event_types import WebhookEventAsyncType
+from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
UPDATE_PAGE_MUTATION = """
@@ -1413,3 +1414,51 @@ def test_update_page_with_single_reference_attributes(
]
for attr_data in attributes_data:
assert attr_data in expected_attributes_data
+
+
+def test_update_page_with_numeric_attribute(
+ staff_api_client, permission_manage_pages, page, numeric_attribute
+):
+ # given
+ query = UPDATE_PAGE_MUTATION
+
+ page_type = page.page_type
+ page_type.page_attributes.all().delete()
+ page_type.page_attributes.add(numeric_attribute)
+
+ numeric_value = 33.12
+ numeric_name = str(numeric_value)
+
+ variables = {
+ "id": to_global_id_or_none(page),
+ "input": {
+ "attributes": [
+ {
+ "id": to_global_id_or_none(numeric_attribute),
+ "numeric": numeric_value,
+ }
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+
+ assert not data["errors"]
+ attributes = data["page"]["attributes"]
+ assert len(attributes) == 1
+ assert attributes[0]["attribute"]["slug"] == numeric_attribute.slug
+ assert len(attributes[0]["values"]) == 1
+ assert attributes[0]["values"][0]["slug"] == f"{page.pk}_{numeric_attribute.pk}"
+ assert attributes[0]["values"][0]["name"] == numeric_name
+
+ assert numeric_attribute.values.filter(
+ name=numeric_name,
+ numeric=numeric_value,
+ ).exists()
diff --git a/saleor/graphql/page/tests/queries/test_pages_with_where.py b/saleor/graphql/page/tests/queries/test_pages_with_where.py
index 2c8b2da1c0..86403b4258 100644
--- a/saleor/graphql/page/tests/queries/test_pages_with_where.py
+++ b/saleor/graphql/page/tests/queries/test_pages_with_where.py
@@ -3,7 +3,6 @@ import datetime
import graphene
import pytest
-from .....attribute import AttributeInputType
from .....attribute.models import AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
from .....page.models import Page, PageType
@@ -333,11 +332,13 @@ def test_pages_query_with_attribute_value_numeric(
attr_value_1 = numeric_attribute_without_unit.values.first()
attr_value_1.name = "1.2"
attr_value_1.slug = "1.2"
+ attr_value_1.numeric = 1.2
attr_value_1.save()
attr_value_2 = numeric_attribute_without_unit.values.last()
attr_value_2.name = "2"
attr_value_2.slug = "2"
+ attr_value_2.numeric = 2
attr_value_2.save()
associate_attribute_values_to_instance(
@@ -1606,7 +1607,7 @@ def test_pages_query_with_non_matching_records(
{
"slug": "page-size",
"value": {
- "numeric": {"range": {"lte": 89}},
+ "slug": {"eq": "10"},
},
},
{
@@ -1761,9 +1762,6 @@ def test_pages_query_with_multiple_attribute_filters(
boolean_attribute.save()
page_type.page_attributes.add(size_page_attribute)
- size_page_attribute.input_type = AttributeInputType.NUMERIC
- size_page_attribute.save()
-
page_type.page_attributes.add(tag_page_attribute)
page_type.page_attributes.add(author_page_attribute)
page_type.page_attributes.add(boolean_attribute)
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index d2e3d5ffeb..c4133d1d77 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -5,10 +5,10 @@ from typing import TypedDict
import django_filters
import graphene
-from django.db.models import Exists, FloatField, OuterRef, Q, Subquery, Sum
+from django.db.models import Exists, OuterRef, Q, Subquery, Sum
from django.db.models.expressions import ExpressionWrapper
from django.db.models.fields import IntegerField
-from django.db.models.functions import Cast, Coalesce
+from django.db.models.functions import Coalesce
from django.utils import timezone
from ...attribute import AttributeInputType
@@ -157,20 +157,24 @@ def _clean_product_attributes_range_filter_input(
)
values = (
AttributeValue.objects.using(database_connection_name)
- .filter(Exists(attributes.filter(pk=OuterRef("attribute_id"))))
- .annotate(numeric_value=Cast("name", FloatField()))
+ .filter(
+ Exists(attributes.filter(pk=OuterRef("attribute_id"))),
+ numeric__isnull=False,
+ )
.select_related("attribute")
)
attributes_map: dict[str, int] = {}
- values_map: defaultdict[str, defaultdict[str, list[int]]] = defaultdict(
+ values_map: defaultdict[str, defaultdict[float, list[int]]] = defaultdict(
lambda: defaultdict(list)
)
for value_data in values.values_list(
- "attribute_id", "attribute__slug", "pk", "numeric_value"
+ "attribute_id", "attribute__slug", "pk", "numeric"
):
attr_pk, attr_slug, pk, numeric_value = value_data
attributes_map[attr_slug] = attr_pk
+ if not numeric_value:
+ continue
values_map[attr_slug][numeric_value].append(pk)
for attr_name, val_range in filter_value:
diff --git a/saleor/graphql/product/mutations/product/product_delete.py b/saleor/graphql/product/mutations/product/product_delete.py
index 729698f968..40d21101de 100644
--- a/saleor/graphql/product/mutations/product/product_delete.py
+++ b/saleor/graphql/product/mutations/product/product_delete.py
@@ -1,8 +1,10 @@
import graphene
+from django.db import transaction
from django.db.models.expressions import Exists, OuterRef
from .....attribute import AttributeInputType
from .....attribute import models as attribute_models
+from .....attribute.lock_objects import attribute_value_qs_select_for_update
from .....core.tracing import traced_atomic_transaction
from .....order import events as order_events
from .....order import models as order_models
@@ -97,7 +99,15 @@ class ProductDelete(ModelDeleteMutation, ModelWithExtRefMutation):
input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES
)
- attribute_models.AttributeValue.objects.filter(
- Exists(assigned_values.filter(value_id=OuterRef("id"))),
- Exists(attributes.filter(id=OuterRef("attribute_id"))),
- ).delete()
+ with transaction.atomic():
+ locked_ids = (
+ attribute_value_qs_select_for_update()
+ .filter(
+ Exists(assigned_values.filter(value_id=OuterRef("id"))),
+ Exists(attributes.filter(id=OuterRef("attribute_id"))),
+ )
+ .values_list("id", flat=True)
+ )
+ attribute_models.AttributeValue.objects.filter(
+ id__in=locked_ids,
+ ).delete()
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py b/saleor/graphql/product/mutations/product_variant/product_variant_delete.py
index 9709cdfbb1..81b4d6a266 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_delete.py
@@ -1,9 +1,11 @@
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models import Exists, OuterRef
from .....attribute import AttributeInputType
from .....attribute import models as attribute_models
+from .....attribute.lock_objects import attribute_value_qs_select_for_update
from .....core.tracing import traced_atomic_transaction
from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirty
from .....order import events as order_events
@@ -142,10 +144,14 @@ class ProductVariantDelete(ModelDeleteMutation, ModelWithExtRefMutation):
@staticmethod
def delete_assigned_attribute_values(instance):
- attribute_models.AttributeValue.objects.filter(
- variantassignments__variant_id=instance.id,
- attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,
- ).delete()
+ with transaction.atomic():
+ locked_ids = attribute_value_qs_select_for_update().filter(
+ variantassignments__variant_id=instance.id,
+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,
+ )
+ attribute_models.AttributeValue.objects.filter(
+ id__in=locked_ids,
+ ).delete()
@staticmethod
def delete_product_channel_listings_without_available_variants(instance):
diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.py
index 33e8276c70..25d5e1b58b 100644
--- a/saleor/graphql/product/tests/mutations/test_product_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_create.py
@@ -2488,6 +2488,7 @@ def test_create_product_with_numeric_attribute_new_attribute_value(
numeric_attribute,
permission_manage_products,
):
+ # given
query = CREATE_PRODUCT_MUTATION
product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
@@ -2495,8 +2496,6 @@ def test_create_product_with_numeric_attribute_new_attribute_value(
product_name = "test name"
product_slug = "product-test-slug"
- values_count = numeric_attribute.values.count()
-
# Add second attribute
product_type.product_attributes.set([numeric_attribute])
attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.id)
@@ -2512,9 +2511,12 @@ def test_create_product_with_numeric_attribute_new_attribute_value(
}
}
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["productCreate"]
assert data["errors"] == []
@@ -2533,7 +2535,7 @@ def test_create_product_with_numeric_attribute_new_attribute_value(
assert values[0]["slug"] == f"{product_pk}_{numeric_attribute.id}"
numeric_attribute.refresh_from_db()
- assert numeric_attribute.values.count() == values_count + 1
+ assert numeric_attribute.values.filter(name=expected_name, numeric=value).exists()
def test_create_product_with_numeric_attribute_existing_value(
diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.py
index 1bda40a17e..059d9496c9 100644
--- a/saleor/graphql/product/tests/mutations/test_product_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_update.py
@@ -640,7 +640,8 @@ def test_update_product_with_numeric_attribute_value(
attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
product_type.product_attributes.add(numeric_attribute)
- new_value = "45.2"
+ numeric_value = 45.2
+ new_value = str(numeric_value)
variables = {
"productId": product_id,
@@ -676,6 +677,10 @@ def test_update_product_with_numeric_attribute_value(
],
}
assert expected_att_data in attributes
+ assert numeric_attribute.values.filter(
+ name=new_value,
+ numeric=numeric_value,
+ ).exists()
updated_webhook_mock.assert_called_once_with(product)
@@ -698,13 +703,14 @@ def test_update_product_with_numeric_attribute_value_new_value_is_not_created(
product_type.product_attributes.add(numeric_attribute)
slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)
value = AttributeValue.objects.create(
- attribute=numeric_attribute, slug=slug_value, name="20.0"
+ attribute=numeric_attribute, slug=slug_value, name="20.0", numeric=20.0
)
associate_attribute_values_to_instance(product, {numeric_attribute.pk: [value]})
value_count = AttributeValue.objects.count()
- new_value = "45.2"
+ numeric_value = 45.2
+ new_value = str(numeric_value)
variables = {
"productId": product_id,
@@ -743,6 +749,7 @@ def test_update_product_with_numeric_attribute_value_new_value_is_not_created(
assert AttributeValue.objects.count() == value_count
value.refresh_from_db()
assert value.name == new_value
+ assert value.numeric == numeric_value
@patch("saleor.plugins.manager.PluginsManager.product_updated")
@@ -2356,7 +2363,8 @@ def test_update_product_with_numeric_attribute_value_by_numeric_field(
attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
product_type.product_attributes.add(numeric_attribute)
- new_value = "45.2"
+ numeric_value = 45.2
+ new_value = str(numeric_value)
variables = {
"productId": product_id,
@@ -2392,6 +2400,9 @@ def test_update_product_with_numeric_attribute_value_by_numeric_field(
],
}
assert expected_att_data in attributes
+ assert numeric_attribute.values.filter(
+ name=new_value, numeric=numeric_value
+ ).first()
updated_webhook_mock.assert_called_once_with(product)
@@ -2412,7 +2423,7 @@ def test_update_product_with_numeric_attribute_by_numeric_field_null_value(
product_type.product_attributes.add(numeric_attribute)
slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)
value = AttributeValue.objects.create(
- attribute=numeric_attribute, slug=slug_value, name="20.0"
+ attribute=numeric_attribute, slug=slug_value, name="20.0", numeric=20.0
)
associate_attribute_values_to_instance(product, {numeric_attribute.pk: [value]})
@@ -2449,13 +2460,14 @@ def test_update_product_with_numeric_attribute_by_numeric_field_new_value_not_cr
product_type.product_attributes.add(numeric_attribute)
slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)
value = AttributeValue.objects.create(
- attribute=numeric_attribute, slug=slug_value, name="20.0"
+ attribute=numeric_attribute, slug=slug_value, name="20.0", numeric=20.0
)
associate_attribute_values_to_instance(product, {numeric_attribute.pk: [value]})
value_count = AttributeValue.objects.count()
- new_value = "45.2"
+ numeric_value = 45.2
+ new_value = str(numeric_value)
variables = {
"productId": product_id,
@@ -2494,6 +2506,7 @@ def test_update_product_with_numeric_attribute_by_numeric_field_new_value_not_cr
assert AttributeValue.objects.count() == value_count
value.refresh_from_db()
assert value.name == new_value
+ assert value.numeric == numeric_value
@patch("saleor.plugins.manager.PluginsManager.product_updated")
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index b059c9147d..dc521537cd 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -1447,6 +1447,7 @@ def test_create_variant_with_numeric_attribute(
warehouse,
numeric_attribute,
):
+ # given
query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
@@ -1454,7 +1455,8 @@ def test_create_variant_with_numeric_attribute(
product_type.variant_attributes.set([numeric_attribute])
variant_slug = numeric_attribute.slug
attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
- variant_value = "22.31"
+ numeric_value = 22.31
+ numeric_name = "22.31"
stocks = [
{
"warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
@@ -1468,13 +1470,17 @@ def test_create_variant_with_numeric_attribute(
"sku": sku,
"stocks": stocks,
"weight": weight,
- "attributes": [{"id": attribute_id, "values": [variant_value]}],
+ "attributes": [{"id": attribute_id, "values": [numeric_name]}],
"trackInventory": True,
}
}
+
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
+
+ # then
content = get_graphql_content(response)["data"]["productVariantCreate"]
assert not content["errors"]
data = content["productVariant"]
@@ -1493,6 +1499,11 @@ def test_create_variant_with_numeric_attribute(
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
created_webhook_mock.assert_called_once_with(product.variants.last())
+ assert numeric_attribute.values.filter(
+ name=numeric_name,
+ numeric=numeric_value,
+ ).first()
+
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_create_variant_with_numeric_attribute_not_numeric_value_given(
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index c5eb746cfd..cafda7f3dd 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -1456,7 +1456,7 @@ def test_update_variant_with_date_time_attribute(
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
-def test_update_variant_with_numeric_attribute(
+def test_update_variant_removes_numeric_attribute_value(
product_variant_updated,
permission_manage_products,
product,
@@ -1501,6 +1501,59 @@ def test_update_variant_with_numeric_attribute(
product_variant_updated.assert_called_once_with(product.variants.last())
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_update_variant_adds_numeric_attribute(
+ product_variant_updated,
+ permission_manage_products,
+ product,
+ product_type,
+ staff_api_client,
+ numeric_attribute,
+ warehouse,
+):
+ # given
+ product_type.variant_attributes.add(numeric_attribute)
+
+ numeric_value = 33.12
+ numeric_name = str(numeric_value)
+
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.id)
+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES
+ variables = {
+ "id": variant_id,
+ "attributes": [
+ {"id": attr_id, "numeric": numeric_name},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantUpdate"]
+ variant.refresh_from_db()
+ data = content["productVariant"]
+
+ assert not content["errors"]
+
+ attribute_data = [
+ attr_data
+ for attr_data in data["attributes"]
+ if attr_data["attribute"]["slug"] == numeric_attribute.slug
+ ][0]
+ assert attribute_data["attribute"]["slug"] == numeric_attribute.slug
+ assert attribute_data["values"][0]["name"] == numeric_name
+
+ assert numeric_attribute.values.filter(
+ name=numeric_name, numeric=numeric_value
+ ).first()
+ product_variant_updated.assert_called_once_with(product.variants.last())
+
+
def test_update_product_variant_with_new_attribute(
staff_api_client,
product_with_variant_with_two_attributes,
diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py b/saleor/graphql/product/tests/queries/test_products_query_with_filter.py
index d815aa91ae..cbd41db5ee 100644
--- a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py
+++ b/saleor/graphql/product/tests/queries/test_products_query_with_filter.py
@@ -138,7 +138,7 @@ def test_products_query_with_filter_numeric_attributes(
category=category,
)
attr_value = AttributeValue.objects.create(
- attribute=numeric_attribute, name="5", slug="5"
+ attribute=numeric_attribute, name="5", slug="5", numeric=5.0
)
associate_attribute_values_to_instance(
@@ -153,7 +153,7 @@ def test_products_query_with_filter_numeric_attributes(
category=category,
)
attr_value = AttributeValue.objects.create(
- attribute=numeric_attribute, name="5", slug="5_X"
+ attribute=numeric_attribute, name="5", slug="5_X", numeric=5.0
)
associate_attribute_values_to_instance(
@@ -370,7 +370,7 @@ def test_products_query_with_filter_by_attributes_values_and_range(
category=category,
)
attr_value_2 = AttributeValue.objects.create(
- attribute=numeric_attribute, name="5.2", slug="5_2"
+ attribute=numeric_attribute, name="5.2", slug="5_2", numeric=5.2
)
associate_attribute_values_to_instance(
@@ -1378,7 +1378,8 @@ def test_products_query_with_filter_search_by_numeric_attribute_value(
numeric_attr_value = numeric_attribute.values.first()
numeric_attr_value.name = "13456"
- numeric_attr_value.save(update_fields=["name"])
+ numeric_attr_value.numeric = 13456
+ numeric_attr_value.save(update_fields=["name", "numeric"])
associate_attribute_values_to_instance(
product_with_numeric_attr,
@@ -1426,7 +1427,8 @@ def test_products_query_with_filter_search_by_numeric_attribute_value_without_un
numeric_attr_value = numeric_attribute.values.first()
numeric_attr_value.name = "13456"
- numeric_attr_value.save(update_fields=["name"])
+ numeric_attr_value.numeric = 13456
+ numeric_attr_value.save(update_fields=["name", "numeric"])
associate_attribute_values_to_instance(
product_with_numeric_attr,
diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_where.py b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
index 78d52344d1..82f7c68944 100644
--- a/saleor/graphql/product/tests/queries/test_products_query_with_where.py
+++ b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
@@ -11,11 +11,7 @@ from .....attribute.tests.model_helpers import (
)
from .....attribute.utils import associate_attribute_values_to_instance
from .....product import ProductTypeKind
-from .....product.models import (
- Product,
- ProductChannelListing,
- ProductType,
-)
+from .....product.models import Product, ProductChannelListing, ProductType
from .....warehouse.models import Allocation, Reservation, Stock, Warehouse
from ....tests.utils import get_graphql_content
@@ -877,7 +873,7 @@ def test_products_filter_by_numeric_attributes(
product_list[1].product_type = product_type
attr_value = AttributeValue.objects.create(
- attribute=numeric_attribute, name="5", slug="5"
+ attribute=numeric_attribute, name="5", slug="5", numeric=5.0
)
associate_attribute_values_to_instance(
product_list[1],
@@ -885,7 +881,7 @@ def test_products_filter_by_numeric_attributes(
)
attr_value = AttributeValue.objects.create(
- attribute=numeric_attribute, name="5", slug="5_X"
+ attribute=numeric_attribute, name="5", slug="5_X", numeric=5.0
)
product_list[2].product_type = product_type
associate_attribute_values_to_instance(
@@ -990,7 +986,7 @@ def test_products_filter_by_attributes_values_and_range(
product_list[1].product_type = product_type
attr_value_2 = AttributeValue.objects.create(
- attribute=numeric_attribute, name="1.2", slug="1_2"
+ attribute=numeric_attribute, name="1.2", slug="1_2", numeric=1.2
)
associate_attribute_values_to_instance(
product_list[1],