Features: 1) Add get_or_create_attribute_safe method for safely creating or retrieving attributes within a transaction;

Fixes: 1) Extend imports with `transaction` to support atomic operations;

Extra: 1) Minor inline comment adjustments for clarity.
This commit is contained in:
Egor Pavlovich Gorbunov 2025-08-18 14:43:54 +03:00
parent 91ebaece07
commit 1308aa47db

View file

@ -4,7 +4,7 @@ from decimal import Decimal
from math import ceil, log10 from math import ceil, log10
from typing import Any from typing import Any
from django.db import IntegrityError from django.db import IntegrityError, transaction
from django.db.models import QuerySet from django.db.models import QuerySet
from core.elasticsearch import process_query from core.elasticsearch import process_query
@ -338,6 +338,29 @@ class AbstractVendor:
self.get_stocks_queryset().delete() # type: ignore [union-attr] self.get_stocks_queryset().delete() # type: ignore [union-attr]
self.get_attribute_values_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: def process_attribute(self, key: str, value: Any, product: Product, attr_group: AttributeGroup) -> None:
if not value: if not value:
return return