Django - 按模板中的某个字段对查询集进行分组

时间:2011-12-30 10:08:07

标签: python django

我有一个表Events,按字段date排序。

我想在模板中打印出事件,但是为每个日期使用单独的div,例如:

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

我该怎么做?


我目前的解决方案是将Event对象放在以日期为键的字典中。这有订购问题,而且不够优雅和低效。

查看:

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]

模板:

{% for date, events in events_dict.items %}
  <div class="content">
    <h1>{{date}}</h1>
    {% for event in events %}
      {% include "partials/event.html" %}
    {% endfor %}
  </div>
{% endfor %}

1 个答案:

答案 0 :(得分:10)

您正在寻找{% regroup %}标记,它正是您想要的。它需要一系列项目(必须事先订购,您的项目)和查找,并通过该查找对序列进行分组。

视图:

events = Event.objects.select_related.all()

模板:

{% 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 %}

(请注意,日期格式字符串不同; the equivalent of %B in strftime is F for the date filter)。