Django: Query using group by and count

0 Comments

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.

01.from django.db.models import Count
02. 
03.brands = Product.objects.get_everything_for_category(category)
04. 
05.# Make it group by manufacturers and count the number of products for each brand betwen $50 and $100
06.brands = brands.filter(price__gte = 50, price__lte = 100)
07. 
09.brands = brands.values('manufacturer').annotate(Count('manufacturer')).order_by('manufacturer')

To access the information within "brands":

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