title: Django aggregation in templates?
body: <p>I'm thinking a bit about the concept of <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/" rel="nofollow noreferrer">Django aggregates.</a> I don't quite "get" how they can be used in my case. Basically i have a three-tier hierarchy of objects in my model, and the lowest object (Bar) contain values I want to aggregate.</p>
  
  <pre><code>class Bar(models.Model):
      amount = models.FloatField()
  
  class Foo(models.Model):
      bars = models.ManyToManyField(Bar)
  
  class MyUser(models.Model):
      foos = models.ManyToManyField(Foo)
  </code></pre>
  
  <p>I want my template to do the equivalent of this:</p>
  
  <pre><code>{% for user in users %}
      &lt;h2&gt;{{ user }}&lt;/h2&gt;
      &lt;table&gt;
          &lt;tr&gt;
              &lt;td&gt;Foo&lt;/td&gt;&lt;
              &lt;td&gt;Average bar amount&lt;/td&gt;
          &lt;/tr&gt;
      {% for foo in user.foos.all %}
          &lt;tr&gt;
              &lt;td&gt;{{ foo }}&lt;/td&gt;
              &lt;td&gt;{{ foo.bars.all.aggregate(Avg('amount')) }}
          &lt;/tr&gt;
      {% endfor %}
      &lt;/table&gt;
  {% endfor %}
  </code></pre>
  
  <p>But of course this template is just pseudo code, it won't work because, I guess, templates are not supposed to do this by design. But on the other hand, having to pre-calculate the average amounts in my view would feel wrong too. How should this problem be approached?</p>
  
  <p>I'm still new to Django so I want to know the "Django way" of doing this :)</p>