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 %}

I tried your code but in the result there is only the 'manufacturer' and not its count (using Django 1.2.3)
ReplyDeleteI'm also using Django 1.2.3 and it seems to be working fine here.
ReplyDeleteJust remember that it pulls the same number of items, but it adds a new element with "__count" to every result.
ie. {{ item.annotatename__count }}