[Django] Built-in Template Tag - regroup

2017-01-27

블로그에서 포스트를 연도별 아카이브를 만들고 싶을 때 장고에 내장된 regroup 태그를 사용하여 구현할 수 있다.

model
class Post(models.Model):
    ...
    date = models.DateTimeField(blank=True, null=True)
	...
views
class PostArchiveListView(ListView):
    model = Post
    template_name = 'blog/archive.html'
    context_object_name = 'posts'

    def get_queryset(self):
        return Post.objects.all().order_by('date').reverse()
template
<div class="archive">
  {% regroup posts by published_date|date:"Y" as posts_by_year %}
  {% for posts in posts_by_year %}
  <div class="archive-posts">
    <div class="archive-year">
      {{ posts.grouper }}
    </div>
    <ul>
      {% for post in posts.list %}
      <li class="archive-post">
        <a href="{% url 'blog:blog_detail' pk=post.pk %}">
          <span class="archive-post-title">
            {{ post.title }} {{ post.date|date:"Y-m-d" }}
          </span>
        </a>
      </li>
      {% endfor %}
    </ul>
  </div>
  {% endfor %}
</div>