1
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)
...
4

2 回答 2

1

首先看一下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
于 2012-09-28T10:17:55.370 回答
1

使用聚合

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)
于 2012-09-28T10:18:41.663 回答