django aggregation: sum then average : <p>Using django's ORM annotate() and/or aggregate(): I want to sum up based on one category field and then average over the category values per date. I tried to do it using two annotate() statements but got a FieldError.</p>

<p>I'm doing this: </p>

<pre><code>queryset1 = self.data.values('date', 'category').annotate(sum_for_field=Sum('category'))
</code></pre>

<p>Which outputs a ValuesQuerySet object with things like (so a sum for each value of category):</p>

<pre><code>[{'category': 'apples', 'date': '2015-10-12', sum_for_field=2000},
 {'category': 'carrots', 'date': '2015-10-12', sum_for_field=5000},
 {'category': 'apples', 'date': '2015-10-13', sum_for_field=3000},
 {'category': 'carrots', 'date': '2015-10-13', sum_for_field=6000}, ...
]
</code></pre>

<p>I then want to average the sum_for_field field for each date to output something like:</p>

<pre><code>[ {'date': '2015-10-12', avg_final: 3500},
{'date': '2015-10-13', avg_final: 4500}, ...
]
</code></pre>

<p>I tried doing this:</p>

<pre><code>queryset2 = queryset1.values('date', 'sum_for_field')
result = queryset2.annotate(avg_final=Avg('sum_for_field'))
</code></pre>

<p>But I got this FieldError: </p>

<pre><code>FieldError: FieldError: Cannot compute Avg('sum_for_field'): 'sum_for_field' is an aggregate
</code></pre>
