/ orders / [<class'decimal.ConversionSyntax'>]的InvalidOperation

时间:2019-11-13 07:54:54

标签: django django-models django-rest-framework django-forms django-views

我要在项目的总价中添加交货成本,但是它不起作用。这两个字段均为Decimal,但会引发此错误InvalidOperation at /orders/ [<class 'decimal.ConversionSyntax'>]。这是交货价格模型

跟踪

  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)

它是FKOrder模型。

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)

这是我到目前为止所尝试的全部。为了清楚起见,首先,用户将产品添加到购物车,然后他们可以在填写订单字段(地址,电话号码等)时进行订购,他们还选择了运输成本,并且此选定的运输成本应添加到总价中。但就我而言,它无法正常工作,但出现上述错误。我该如何解决这个问题?有什么帮助吗?提前致谢!

1 个答案:

答案 0 :(得分:0)

已解决

我的错误与序列化程序有关,因为我将price_of_delivery设置为DecimalField,并且在视图中我也转换为Decimal。我刚刚将serializers.DecimalField更改为serializers.CharField,并且一切正常。