I am going to add delivery cost to total price in project but it does not work. Both fields are Decimal but it throws this error InvalidOperation at /orders/ [<class 'decimal.ConversionSyntax'>]. Here is Delivery price model
Traceback
File "/home//venv/lib/python3.7/site-packages/rest_framework/fields.py", line 1115, in to_representation
value = decimal.Decimal(str(value).strip())
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
models.py
class DeliveryPrice(models.Model):
shipping_name = models.CharField(max_length=255, blank=True, null=True)
shipping_charge = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
and it is the FK to Order model.
serializers.py
class OrderSerializer(serializers.ModelSerializer):
price_of_delivery = serializers.DecimalField(max_digits=10, decimal_places=2)
class Meta:
model = Order
fields = ['phone', 'address', 'price_of_delivery']
def create(self, validated_data):
price_of_delivery = validated_data.pop('price_of_delivery')
price_instance, created = DeliveryPrice.objects.get_or_create(shipping_charge=price_of_delivery)
order_instance = Order.objects.create(**validated_data, price_of_delivery=price_instance)
return order_instance
views.py
total_aggregated_dict = cart.aggregate(
total_price=Sum(F('quantity') * F('product__price'), output_field=DecimalField()))
print(total_aggregated_dict)
order_total = total_aggregated_dict['total_price']
delivery_price = self.request.data['price_of_delivery']
print(delivery_price)
final_total = Decimal(order_total) + Decimal(delivery_price)
print(final_total)
order = serializer.save(user=user, total_price=final_total)
this is all what I have tried so far. To be clear, firstly, user adds product to cart then they can order when they fill order fields (address, phone number, etc) they also select shipping cost and this selected shipping cost should be added to total price. But in my case it is not working I am getting error above shown. How can i tackle this issue? Any help please? Thanks in advance!
Solved
my mistake was with serializer because I am setting price_of_delivery to DecimalField and in the views I am also converting to Decimal. I just have changed serializers.DecimalField to serializers.CharField and everything is working well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With