diff --git a/core/vendors/__init__.py b/core/vendors/__init__.py index 7e7d60f8..274e28e8 100644 --- a/core/vendors/__init__.py +++ b/core/vendors/__init__.py @@ -4,7 +4,7 @@ from decimal import Decimal from math import ceil, log10 from typing import Any -from django.db import IntegrityError +from django.db import IntegrityError, transaction from django.db.models import QuerySet from core.elasticsearch import process_query @@ -338,6 +338,29 @@ class AbstractVendor: self.get_stocks_queryset().delete() # type: ignore [union-attr] self.get_attribute_values_queryset().delete() # type: ignore [union-attr] + def get_or_create_attribute_safe(self, *, name: str, attr_group: AttributeGroup) -> Attribute: + + key = name[:255] + try: + attr = Attribute.objects.get(name=key) + except Attribute.DoesNotExist: + try: + with transaction.atomic(): + attr = Attribute.objects.create( + name=key, + group=attr_group, + is_active=True, + value_type="string", + ) + except IntegrityError: + attr = Attribute.objects.get(name=key) + + if not attr.is_active: + attr.is_active = True + attr.save(update_fields=["is_active"]) + + return attr + def process_attribute(self, key: str, value: Any, product: Product, attr_group: AttributeGroup) -> None: if not value: return