【问题标题】:Get aggregate in a template在模板中获取聚合
【发布时间】:2017-03-15 14:29:59
【问题描述】:

我有这个 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 %}

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

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

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

【问题讨论】:

  • 呃,关注aggregation docs?你到底在哪里遇到问题?
  • @DanielRoseman 我用我尝试过的方法更新了问题,问题在于我有另一个模型(我之前发布了不正确的模型)。

标签: django


【解决方案1】:

你应该使用.annotate (look 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 %}

【讨论】:

  • 我搞定了。有没有办法过滤掉一些orders?
  • @BartFriederichs 请举例说明你想要什么
  • 我只想统计有一定状态的订单。
  • @BartFriederichs 也许你可以用When object来做到这一点
  • @BartFriederichs 看看this question
【解决方案2】:

经过一番折腾,我发现这是可行的:

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

然后在模板中使用这个:

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

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多