[Answer]-Django template rendering relational modelobject names without duplicates


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):

    {% for object in object_list %}
        <td>{{ object.station__region}} </td>
        <td>{{ object.station__name }}</td>
        <td>{{ object.count }}</td>

    {% endfor %}

Leave a comment