Python ';十进制。十进制';对象不可编辑django发生错误
我在Django模型中尝试循环并获取十进制对象的总数时出错,尝试了很多解决方案都失败了。错误是Python ';十进制。十进制';对象不可编辑django发生错误,python,django,django-models,Python,Django,Django Models,我在Django模型中尝试循环并获取十进制对象的总数时出错,尝试了很多解决方案都失败了。错误是 'decimal.Decimal' object is not iterable 这是模型和对象 from django.db import models class Product(models.Model): name = models.CharField(max_length=50, null=True) price = models.DecimalField(max_dig
'decimal.Decimal' object is not iterable
这是模型和对象
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=50, null=True)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return self.name
class Order(models.Model):
total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
timestamp = models.DateTimeField(auto_now=True)
def __str__(self):
return 'Order {0}'.format(self.id)
@property
def order_prices(self):
order = Decimal(0)
for o in float(self.total_price):
order += o
return float(order)
@property
def product_name(self):
product_name = []
for b in self.orderitem_set.all():
product_name.append(b.total_name)
return product_name
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
order = models.ForeignKey(Order, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
@property
def total_name(self):
product_name = []
for p in self.product.name:
product_name.append(p)
b = "".join(product_name)
return b
order model属性的order_price对象出错
def订单价格(自身):
queryset=self.orderitem\u set.all().aggregate(
总价=models.Sum(‘产品价格’)
返回查询集['总价']
self.total\u price
返回一个DecimalField
,因此self中o的。total\u price
没有多大意义。您不应该在for循环中使用self.total\u price
,因为它来自DecimalField
我假设您有另一个带有项目的模型?你要做的是把一个订单中所有商品的总价相加,作为订单的一个属性。那么,关于如何把所有的总价相加,你有什么建议吗?是的@Lewis我想把所有商品的总价相加,我有另一个带有产品/价格的模型。。但不是这种模式的外国钥匙