在我的网站中,我有一个时间线视图,用户可以看到所有有组织的事件(即将到来和过去),为此我创建了一个具有DateTimeField的事件模型,现在我尝试将结果分组到在模板中渲染它们。所需的输出是:
- 2014
-- January
---- event1
---- event2
-- February
---- event1
---- event2
....
- 2015
-- January
....
我尝试按年分组:
events = {}
last_year = None
current_year_events = []
for event in ProofEvent.objects.all().order_by("date"):
year = event.date.year
if year != last_year:
current_year_events.append(event)
events[year] = current_year_events
last_year = year
current_year_events = []
print event.title
else:
current_year_events.append(event)
print event.title
print events
答案 0 :(得分:3)
如果您尝试仅为模板渲染分组事件,则不需要。您可以传递一个简单的事件列表,并使用{% ifchanged %}
模板标记:
{% for event in events %}
{% ifchanged %}<h2>{{ event.date|date:"Y" }}</h2>{% endifchanged %}
{% ifchanged %}<h3>{{ event.date|date:"F" }}</h3>{% endifchanged %}
<div>{{ event.title }}</div>
{% endfor %}