Django - Grouping querysets by a certain field in template

后端 未结 1 1574
梦毁少年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 %}
        

    {{ date.grouper|date:"d F Y" }}

    {% for event in date.list %} {% include "partials/event.html" %} {% endfor %}
    {% endfor %}

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

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