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:
@@ -251,7 +251,7 @@ class OrderCreateSerializer(serializers.Serializer):
|
||||
|
||||
# přidame fieldy, které nejsou vyplněné
|
||||
for field in required_fields:
|
||||
if attrs.get(field) not in required_fields:
|
||||
if not attrs.get(field):
|
||||
missing_fields.append(field)
|
||||
|
||||
if missing_fields:
|
||||
@@ -307,10 +307,13 @@ class OrderCreateSerializer(serializers.Serializer):
|
||||
|
||||
|
||||
# -- Slevové kódy --
|
||||
# Discount codes need to be added before payment/final save because calculate_total_price uses them
|
||||
if codes:
|
||||
discounts = list(DiscountCode.objects.filter(code__in=codes))
|
||||
if discounts:
|
||||
order.discount.add(*discounts)
|
||||
# Save to recalculate total with discounts
|
||||
order.save(update_fields=["total_price", "updated_at"])
|
||||
|
||||
|
||||
|
||||
@@ -324,7 +327,7 @@ class OrderCreateSerializer(serializers.Serializer):
|
||||
|
||||
# přiřadíme k orderu
|
||||
order.payment = payment
|
||||
order.save(update_fields=["payment"])
|
||||
order.save(update_fields=["payment", "updated_at"])
|
||||
|
||||
return order
|
||||
|
||||
|
||||
Reference in New Issue
Block a user