[Fixed]-Display queryset results by month in template

1👍

itertools.groupby() is an excellent tool for grouping your list.

First you should order your object by the attribute that you are grouping by

tenant_queryset = Tenant.objects.order_by('contract_end')

Grouping by month can be achieved by using itertools.groupby and formatting the date as the month’s name as a string date.strftime('%B')

context = {
    "expired_list": itertools.groupby(
        expired_list, 
        lambda t: t.contract_end.strftime('%B')
    )
}

You can then loop over the months and the tenants for that month in the template like so

{% for month, tenants in expired_list %}
<h3>{{ month }}</h3>
<table>
    {% for tenant in tenants %}
    <tr>
        <td>{{ tenant.first_name }}</td>
        <td>{{ tenant.telephone }}</td>
        <td>{{ tenant.contract_end }}</td>
    </tr>
    {% endfor %}
</table>
{% endfor %}

Leave a comment