在模板中获取聚合

时间:2016-11-02 10:08:18

标签: django

我有这个Django模型:

class Location(models.Model):
    name = models.CharField(primary_key=True, max_length=100)
    customer = models.OneToOneField(Customer, default=None)

class Customer(models.Model):
    name = models.CharField(primary_key=True, max_length=100)

class Order(models.Model):
    amount = models.PositiveIntegerField(default=0)
    customer = models.ForeignKey(Customer, default=0)
在我看来,我得到这样的话:

locations = models.Location.objects.all()

,模板将它们列为:

{% for location in locations %}
    {{ location.customer.name }}
{% endfor %}

我想添加与该客户相关的所有amount的所有Order的总和,如:

{% for location in locations %}
    {{ location.customer.name }} ordered {{ location.customer.orders.sum(amount) }} items
{% endfor %}

根据this question,我应该在视图中这样做,但是如何?

2 个答案:

答案 0 :(得分:1)

您应该使用.annotatelook in docs):

from django.db.models import Count

customers = models.Customer.objects.annotate(orders_count=Count('order'))

然后在模板中你可以像这样使用它:

{% for customer in customers %}
    {{ customer.name }} ordered {{ customer.orders_count }} items
{% endfor %}

答案 1 :(得分:0)

经过一番徘徊,我发现这有效:

locations = models.Location.objects.annotate(num_order=Count('customer__order'))

然后在模板中使用它:

{% for location in locations %}
    {{ location.customer.name }} ordered {{ location.num_order }} items
{% endfor %}