Django Query Count group by
<p>I have read this  thread: <a href="https://stackoverflow.com/questions/2470260/django-query-count-and-group-by">Django query: Count and Group BY</a> and read <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/" rel="nofollow noreferrer">django queryset doc</a></p>

<p>I found two way to implement SQL <code>COUNT GROUP BY</code>.</p>

<p><strong>(1) <code>distinct</code></strong></p>

<pre><code>note_list = Note.objects.filter(user=user).order_by('tag').values('tag').distinct()
for note in note_list:
    print note
</code></pre>

<p>worked for me.</p>

<p><strong>(2) <code>annotate</code></strong></p>

<pre><code>qs = Note.objects.filter(user=user).annotate(Count('tag')) 
for e in qs:
    print e.tag__count
</code></pre>

<p><em>NOT</em> worked. <code>count</code> always <code>1</code>.</p>

<p>When I use <code>distinct</code> but not <code>order_by</code>, it also not work. I had tried other way, also not worked.</p>

<p>django version: 1.8</p>

<p>MySQL version: 5.6.29</p>

<p><strong>UPDATE:</strong></p>

<pre><code>Note.objects.filter(user=user).order_by('tag').values('tag').annotate(count=Count('tag'))
</code></pre>

<p>work well for me!</p>