Add custom exception handler and improve order logic

Introduced a custom DRF exception handler to convert Django ValidationError to DRF ValidationError and registered it in settings. Improved Order model's calculate_total_price method to avoid accessing related fields before the object is saved. Updated OrderCreateSerializer to save the order after adding discounts and payment, ensuring total price is recalculated. Added utility functions and a rounded DateTime field in a new utils.py.
This commit is contained in:
2026-02-01 03:17:49 +01:00
parent 3e4d58f80d
commit f9636d1464
4 changed files with 59 additions and 6 deletions

View File

@@ -212,7 +212,8 @@ class Order(models.Model):
def calculate_total_price(self):
carrier_price = self.carrier.get_price() if self.carrier else Decimal("0.0")
if self.discount.exists():
# Check if order has been saved (has an ID) before accessing many-to-many relationships
if self.pk and self.discount.exists():
discounts = list(self.discount.all())
total = Decimal('0.0')
@@ -227,8 +228,10 @@ class Order(models.Model):
total = Decimal('0.0')
# getting all prices from order items (without discount) - using VAT-inclusive prices
for item in self.items.all():
total = total + (item.product.get_price_with_vat() * item.quantity)
# Only try to access items if order has been saved
if self.pk:
for item in self.items.all():
total = total + (item.product.get_price_with_vat() * item.quantity)
return total + carrier_price