Render Counter Collections Sort Order
<p>I can't figure out how to display a collections.Counter in the right order in Django: When i use Counter().most_common(5) it should give me the 5 most common keys in order. But it does not.</p>

<p>I've got this:</p>

<pre><code>users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_common(5)) 
return render(request,'admin/stats/stats.html', { 'users_cities': users_cities, }
</code></pre>

<p>But when i loop through them in the template, they arent sorted:</p>

<pre><code>{% for label , counter in users_cities.items %}
  {% if label %}
  &lt;tr&gt;
    &lt;th&gt;{{ label }}&lt;/th&gt;&lt;td&gt; {{ counter }}&lt;/td&gt;
  &lt;/tr&gt;
  {% endif %}
{% endfor %}
</code></pre>

<p>So where is my mistake?</p>

<p>It is nice that you got the answer. But I wont prefer to go for Counter as we have annotate in Django.</p>

<p>When you use Counter the code will be</p>

<pre><code>users_cities = Counter(User.objects.all().values_list('city', flat=True)).most_common(5)
</code></pre>

<p>which results in an SQL query of </p>

<pre><code>SELECT city FROM user
</code></pre>

<p>You can use annotate instead.</p>

<pre><code>users_cities = User.objects.all().values('city').annotate(count = Count('city')).order_by('-count')[:5]
</code></pre>

<p>This results in a query of </p>

<pre><code>SELECT city, COUNT(user.city) AS count FROM user GROUP BY user.city
</code></pre>

<p>ORDER BY count DESC LIMIT 5</p>

<p>And the query time will also be less.</p>

<p>I hope that this helps. :)</p>

python django collections