From 171f2cb20f8e1afd672a67c93dd6103fe8a21a39 Mon Sep 17 00:00:00 2001 From: Egor fureunoir Gorbunov Date: Tue, 8 Jul 2025 16:32:01 +0300 Subject: [PATCH] Features: 1) Add `update_order_products_statuses` method for bulk updating product statuses; 2) Wrap order creation logic in atomic transaction to ensure integrity. Fixes: 1) Add missing `transaction` import in `core/models.py`. Extra: 1) Refactor order product status updates to use the new method; 2) Enhance readability and maintainability of order processing logic. --- core/models.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/core/models.py b/core/models.py index eb05e54a..6227b25d 100644 --- a/core/models.py +++ b/core/models.py @@ -9,6 +9,7 @@ from django.contrib.postgres.indexes import GinIndex from django.core.cache import cache from django.core.exceptions import BadRequest, ValidationError from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import transaction from django.db.models import ( CASCADE, PROTECT, @@ -1617,11 +1618,12 @@ class Order(ExportModelOperationsMixin("order"), NiceModel): # type: ignore [mi case "balance": if order.user.payments_balance.amount < amount: raise NotEnoughMoneyError(_("insufficient funds to complete the order")) - order.status = "CREATED" - order.buy_time = timezone.now() - order.order_products.all().update(status="DELIVERING") - order.save() - return order + with transaction.atomic(): + order.status = "CREATED" + order.buy_time = timezone.now() + order.update_order_products_statuses("DELIVERING") + order.save() + return order case "payment": order.status = "PAYMENT" order.save() @@ -1708,6 +1710,9 @@ class Order(ExportModelOperationsMixin("order"), NiceModel): # type: ignore [mi self.status = "FINISHED" self.save() + def update_order_products_statuses(self, status: str = "PENDING"): + self.order_products.update(status=status) + def bulk_add_products(self, products: list[dict[str, Any]]): for product in products: self.add_product(