Django - Grouping querysets by a certain field in template

后端 未结 1 1562
梦毁少年i
梦毁少年i 2021-01-12 09:37

I have a table Events, ordered by a field date.

I want to print out the events in the template, but using a separate div for each date, e.g

相关标签:
1条回答
  • 2021-01-12 10:23

    You're looking for the {% regroup %} tag, which does exactly what you want. It takes a sequence of items (it has to be ordered beforehand, which yours is) and a lookup and groups the sequence by that lookup.

    view:

    events = Event.objects.select_related.all()
    

    template:

    {% regroup events by date as events_by_date %}
    {% for date in events_by_date %}
        <div class="content">
        <h1>{{ date.grouper|date:"d F Y" }}</h1>
        {% for event in date.list %}
            {% include "partials/event.html" %}
        {% endfor %}
        </div>
    {% endfor %}
    

    (Notice that the date format string is different; the equivalent of %B in strftime is F for the date filter).

    0 讨论(0)
提交回复
热议问题