Django: Query using group by and count

To group the results by a certain field and count the number of matches in each row, use values() to group and annotate(Count()) to count.

from django.db.models import Count

brands = Product.objects.get_everything_for_category(category)

# Make it group by manufacturers and count the number of products for each brand betwen $50 and $100
brands = brands.filter(price__gte = 50, price__lte = 100)

# http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values
brands = brands.values('manufacturer').annotate(Count('manufacturer')).order_by('manufacturer')

To access the information within "brands":

{% for brand in brands %}
  <li>{{brand.manufacturer}} ({{brand.manufacturer__count}})</li>
{% endfor %}
 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog