1👍
✅
What you want to use is the annotate
function in combination with the values
function:
from django.db.models import Count
tips = StationTip.objects.filter(published=True).values('station__name', 'station__region').annotate(count=Count('id'))
This will create a list with a dictionary for each unique combination of station.name
and station.region
, with an extra key count
and the number of occurrences.
And in your template (if you pass tips as object_list):
<table>
{% for object in object_list %}
<tr>
<th>Region</th>
<th>Station</th>
<th>Count</th>
</tr>
<tr>
<td>{{ object.station__region}} </td>
<td>{{ object.station__name }}</td>
<td>{{ object.count }}</td>
</tr>
{% endfor %}
</table>
👤knbk
Source:stackexchange.com