Skip to content

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

Raise formatted error when trying to assign assigned media to variant (#9496)

l3str4ngeb0672eea0422
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index b8fe11c330..4a5d8a3cfc 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1812,7 +1812,16 @@ class VariantMediaAssign(BaseMutation):
# check if the given image and variant can be matched together
media_belongs_to_product = variant.product.media.filter(pk=media.pk).first()
if media_belongs_to_product:
- media.variant_media.create(variant=variant)
+ _, created = media.variant_media.get_or_create(variant=variant)
+ if not created:
+ raise ValidationError(
+ {
+ "media_id": ValidationError(
+ "This media is already assigned",
+ code=ProductErrorCode.MEDIA_ALREADY_ASSIGNED,
+ )
+ }
+ )
else:
raise ValidationError(
{
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 5d33e2b83f..3ffd57f9c5 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -10103,6 +10103,7 @@ ASSIGN_VARIANT_QUERY = """
errors {
field
message
+ code
}
productVariant {
id
@@ -10151,12 +10152,11 @@ def test_assign_variant_media_second_time(
)
# then
- content = get_graphql_content_from_response(response)
+ content = get_graphql_content_from_response(response)["data"]["variantMediaAssign"]
assert "errors" in content
- assert (
- "duplicate key value violates unique constraint"
- in content["errors"][0]["message"]
- )
+ errors = content["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.MEDIA_ALREADY_ASSIGNED.name
def test_assign_variant_media_from_different_product(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a0a27b06f7..356c9623ef 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -11421,6 +11421,7 @@ enum ProductErrorCode {
ATTRIBUTE_ALREADY_ASSIGNED
ATTRIBUTE_CANNOT_BE_ASSIGNED
ATTRIBUTE_VARIANTS_DISABLED
+ MEDIA_ALREADY_ASSIGNED
DUPLICATED_INPUT_ITEM
GRAPHQL_ERROR
INVALID
diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.py
index 747669d1ca..ce1098d9ae 100644
--- a/saleor/product/error_codes.py
+++ b/saleor/product/error_codes.py
@@ -6,6 +6,7 @@ class ProductErrorCode(Enum):
ATTRIBUTE_ALREADY_ASSIGNED = "attribute_already_assigned"
ATTRIBUTE_CANNOT_BE_ASSIGNED = "attribute_cannot_be_assigned"
ATTRIBUTE_VARIANTS_DISABLED = "attribute_variants_disabled"
+ MEDIA_ALREADY_ASSIGNED = "media_already_assigned"
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
GRAPHQL_ERROR = "graphql_error"
INVALID = "invalid"