呈现按日期分组的帖子列表

Render lists of posts grouped by date

我的网站每天有多个 post。我想呈现 post 的列表,但我希望 post 按日期分组,而不仅仅是按日期排序,以便每个日期都有自己的 post 列表。

我向模板发送了一个 post 的列表,post.posted_on 是创建 post 时的时间戳。如何呈现按日期分组的 post?

您可以使用 itertools.groupby 按天对帖子进行分组。按 posted_on 降序排列帖子,然后使用 groupby 和当天的关键字。遍历组,并遍历每个组中的帖子,以构建包含帖子列表的部分。

from itertools import groupby
# sort posts by date descending first
# should be done with database query, but here's how otherwise
posts = sorted(posts, key=lambda: post.posted_on, reverse=True)
by_date = groupby(posts, key=post.posted_on.date)
return render_template('posts.html', by_date=by_date)
{% for date, group in by_date %}<div>
    <p>{{ date.isoformat() }}</p>
    {% for post in group %}<div>
        {{ post.title }}
        ...
    </div>{% endfor %}
</div>{% endfor %}