按年、月列出博客条目
我想做类似这样的事情:
Entries.objects.values('date.year','date.month')
但是这一行代码是不对的。我该怎么按年、按月列出博客文章,并在模板中显示出来呢?
谢谢!
4 个回答
1
这里有一段我博客里的代码,主要是用来列出某一年所有的博客文章:
Entries.objects.filter(draft=drafts).filter(posted_date__year=year).order_by(order_by)
在上面的代码中:
drafts
是一个布尔值,用来决定是否显示已完成的项目。year
是你选择的年份。order_by
是用来排序的列名。
你可以很容易地修改这个例子,让它也能包含月份。上面的代码展示了你可以把多个筛选条件组合在一起使用。
4
你可以试试内置的 regroup 标签。
在你的视图中:
archives = Entries.objects.all()
在你的模板中:
{% regroup archives by date.month as entries_by_month %}
{% for entries in entries_by_month %}
<h1>{{ entries.list.0.date|date:"F Y" }}</h1>
<ul>
{% for entry in entries.list %}
<li>{{ entry.title }}</li>
{% endfor %}
</ul>
{% endfor %}
9
如果你在你的视图中设置了
entry_list = Entry.objects.order_by('pub_date')
那么你可以在模板中使用 ifchanged 这个标签来显示月份和年份。
{% for entry in entry_list %}
{% ifchanged %}<h3>{{entry.pub_date|date:"Y"}}</h3>{% endifchanged %}
{% ifchanged %}<h4>{{entry.pub_date|date:"F"}}</h4>{% endifchanged %}
<p>{{entry.title}}</p>
{% endfor %}
另一个对博客归档很有用的 Django 查询集方法是 dates。
举个例子,
entry_months = Entry.objects.dates('pub_date','month','DESC')
这个方法会返回一个 DateQuerySet
,里面包含每个月有博客文章的 datetime.datetime
对象。你可以在模板中使用这个查询集来创建指向每月归档页面的链接。