如何获得杂志中所有项目的价格总和? - django ORM

时间:2012-09-28 09:52:50

标签: python django django-models django-orm

class Item(models.Model):
    name = models.CharField(max_length=50)
    item_price = models.DecimalField(max_digits=5, decimal_places=2)

class Magazine(models.Model):
    name = models.CharField(max_length=50)
    items = models.ManyToManyField('Item', blank=True, null=True)
    owner = models.ForeignKey(User, related_name='u_item')

如何获得杂志中所有项目的价格总和?

在观点中:

...
    user = request.user
    magazins = Magazine.objects.filter(owner= user)
...

2 个答案:

答案 0 :(得分:1)

首先看一下aggregations in Django

它可能如下所示:

from django.db.models import Sum
owners_magazines = Magazine.objects.filter(owner='Your owner')
total = 0;
for magazine in owners_magazines:
    item_values_with_total = magazine.items.values().annotate(total=Sum('item_price'))
    total += <Read appropriately from item_values_with_total>

您可以进一步尝试将事物分组在一起。返回的值将有一个名为total的字段,该字段将具有所需的总和。

编辑 -

您可以尝试使用非ORM解决方案来更好地理解

from django.db.models import Sum
    owners_magazines = Magazine.objects.filter(owner='Your owner')
    total = 0;
    for magazine in owners_magazines:
        all_items = magazines.items_set.all()
        for item in all_items:
            total += item.item_price

    print total

答案 1 :(得分:1)

使用aggregation

from django.db.models import Sum

for m in Magazine.objects.all():
   total = m.items_set.all().annotate(total=Sum('item_price'))
   print 'Total cost for items in {0} is {1}'.format(m,total)