开发者

Sum values in a dictionary

Working on an Django app which can store equipments.

class E开发者_Go百科quipment(models.Model):
   price = models.DecimalField(max_digits = 12, decimal_places=2)

I want to add All equipment prices. I have tried to do something like this:

total = Equipment.objects.aggregate(Sum('price'))

but if do this I cannot get to do any mathematical sums with this because it saying it's a dictionary.

I want my price value to be a number because I want to be able to do sums with the total variable.


You need to add .all() See Django Aggregation

Equipment.objects.all().aggregate(Sum('price'))

EDIT: You do not need the .all() in this case, you can get the value out of the dictionary returned by accessing the value returned in the dict:

total = Equipment.objects.aggregate(price_sum=Sum('price'))
total_price = total['price_sum']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜