计算Django中模型属性的总和 [英] Calculate the sum of model properties in Django
问题描述
我有一个模型 Order
,该模型具有一个根据计算
。 order_total
的属性通过外键链接的OrderItem
I have a model Order
which has a property that calculates an order_total
based on OrderItem
s linked by foreign key.
我想计算 Order $的总数。 c $ c>实例的
order_total
个属性。
I would like to calculate the sum of a number of Order
instances' order_total
properties.
有没有办法做到这一点?
Is there a way of doing this?
class Order(models.Model):
customer = models.ForeignKey(Customer)
placed = models.DateField()
...
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
order_total = property(get_total_cost)
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name="items")
product = models.ForeignKey(Product, related_name="order_items")
quantity = models.PositiveIntegerField(default=1)
...
def get_cost(self):
return self.product.price * self.quantity
这是我的查询:
>>> Order.objects.all().aggregate(Sum("order_total"))
哪个会返回此错误:
django.core.exceptions.FieldError: Cannot resolve keyword 'order_total' into field. Choices are: placed, customer, customer_id, id, items, paid
推荐答案
您需要使用双下划线 __ 从 OrderItem 模型中以 order 作为查找字段的order_total的外键查找:
You need to use double underscore __ for foreign key lookup of order_total from OrderItem model with order as the lookup field:
odrerObj = OrderItem.objects.all().aggregate(sum_order = Sum("order__order_total"))
但是如果您需要 Order oject的order_total属性的总和,则可以使用以下内容:
But if you need sum of Order oject's order_total property, you can use something like this :
order_list = Order.objects.all()
sum = 0
for item in order_list :
sum = sum + item.order_total()
print sum
这篇关于计算Django中模型属性的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!