我得到 decimal.InvalidOperation:[<class 'decimal.ConversionSyntax'>]

I got decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

views.py


@api_view(["POST", "GET"])
@permission_classes([IsAuthenticated])
def add_order(request, pk):
    print(request.user)
    customer = md.Customer.objects.get(pk=pk)
    if request.method == "POST":
        description = request.data['description']
        price = request.data['price']
        order = md.Order.objects.create(customer=customer,
                                        date_created=zt.now(),
                                        description=description,
                                        price=float(price),
                                        customer_total_when_created=customer.total_owe[0]
                                        )
        try:
            is_paid = request.data['is_paid']
            if is_paid == "on":
                who_paid = request.data['who_paid']
                payment_method = request.data['payment_method']
                who_took_money = request.user
                if who_paid == customer.name:
                    order.who_paid = customer
                elif who_paid == customer.parent:
                    order.who_paid = customer.parent
                order.payment_method = payment_method
                order.who_took_money = who_took_money
                order.date_paid = zt.now()
            customer.total = customer.total_owe
            customer.save()
            order.save()

        
        except:
            print("no payment succeed")
        order_api = OrderSerializer(order)
        return Response(order_api.data)
    customer_api = CustomerSerializer(customer)
    parent_api = CustomerSerializer(customer.parent)
    context = {
        "customer": customer_api.data,
        "parent":parent_api.data,
        "sample": [
            {"description": "secreal", "price": "12.21", "is_paid": "on", "who_paid": "azra", "payment_method": "CARD"}
        ]
    }
    return Response(context)

models.py

class Order(models.Model):
    payment_method_list = [("CASH","CASH"),("CARD","CARD")]
    customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True,)
    who_paid = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True, related_name='%(class)s_requests_created')
    who_took_money = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True, related_name='who_took_money')


    payment_method = models.CharField(choices=payment_method_list,max_length=4,default="CASH",blank=True,null=True)
    date_paid = models.DateTimeField(blank=True,null=True)
    date_created = models.DateTimeField(blank=True, null=True)
    date_modified = models.DateTimeField(blank=True, null=True, auto_now=True)

    is_paid = models.BooleanField(default=False, blank=True,null=True)
    customer_total_when_paid = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
    customer_total_when_created = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
    description = models.TextField(blank=True,null=True)
    price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)


    def __str__(self):
        return self.description[0:12]



from django.db.models.signals import post_save
def update_total_owe_created_order(sender,instance,created,**kwargs):
    
    if created:
        order = instance
        customer = order.customer
        customer.total = customer.total_owe[0]
        customer.save()

post_save.connect(update_total_owe_created_order,sender=Order)

def update_total_owe_updated_order(sender,instance,created,**kwargs):
    if created==False:
        order = instance
        customer = order.customer
        customer.total = customer.total_owe[0]
        customer.save()
post_save.connect(update_total_owe_updated_order,sender=Order)

我有一个应用程序,您可以将订单发送到该应用程序并将其添加到数据库中。 它只允许经过身份验证的用户添加订单;所以它显示了谁添加了那个订单。我可以通过 JWT 身份验证获得 request.user 但无法保存模型。当我发送 API post 请求时,出现该错误。我可以让用户使用令牌,但它给了我那个错误。我不知道为什么。我正在使用 postman。我没有正常得到它,但是当我使用 postman 时它不起作用。

    ret = super().data
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 253, in data
    self._data = self.to_representation(self.instance)
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\fields.py", line 1127, in to_representation
    value = decimal.Decimal(str(value).strip())
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

您的 Order 模型中的 price 是一个小数字段,但您在创建 float 时将 post 请求中的 price =13=]对象。

price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)

price 应该是 Decimal 对象而不是 float

order = md.Order.objects.create(customer=customer,
                                        date_created=zt.now(),
                                        description=description,
                                        price=Decimal(price),
                                        customer_total_when_created=customer.total_owe[0]
                                        )

customer_total_when_created 也应该是一个 Decimal 实例,但您还没有 posted 具有 total_owe.[=24= 的 Customer 模型]