Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

python - Django - Grouping querysets by a certain field in template

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

<div class="content">
  <h1>December 30th</h1>
  <!-- div for Event 1 from December 30th -->
  <!-- div for Event 2 from December 30th -->
</div>

<div class="content">
  <h1>December 31st</h1>
  <!-- div for Event 1 from December 31st -->
  <!-- div for Event 2 from December 31st -->
  <!-- div for Event 3 from December 31st -->
</div>

How do I do this?


My current solution is to put the Event objects in a dictionary with the date as the key. This has ordering issues and is inelegant and inefficient.

View:

events = Event.objects.select_related().all()

events_dict={}
for event in events:
    date=event.date.strftime('%d %B %Y')
    if date in events_dict:
        events_dict[date].append(event) 
    else:
        events_dict[date] = [event]

Template:

{% for date, events in events_dict.items %}
  <div class="content">
    <h1>{{date}}</h1>
    {% for event in events %}
      {% include "partials/event.html" %}
    {% endfor %}
  </div>
{% endfor %}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...