按年份,月份列出博客条目 [英] Listing blog entries by year,month
问题描述
我想做这样的事情:
Entries.objects.values('date.year','date。月')
但此行无效。如何按年份和月份列出博客条目并显示在模板中?
谢谢!
如果您设置
entry_list = Entry.objects.order_by('pub_date')$ b $您可以使用 $ b 在您的视图中显示模板中的月份和年份, /docs.djangoproject.com/en/dev/ref/templates/builtins/#ifchangedrel =noreferrer> ifchanged 模板标签。
{%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查询方法是日期。
例如
entry_months = Entry .objects.dates('pub_date','month','DESC')
返回一个 DateQuerySet
的 datetime.datetime
每个月有博客条目的对象。您可以在模板中使用此查询器来创建每月归档页面的链接。
I want to do something like this:
Entries.objects.values('date.year','date.month')
but this line is not valid. How can I list blog entries by year,month and display them in template?
Thanks!
解决方案 If you set
entry_list = Entry.objects.order_by('pub_date')
in your view, you can display the months and years in the template using the ifchanged template tag.
{% 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 %}
Another useful Django queryset method for blog archives is dates.
For example
entry_months = Entry.objects.dates('pub_date','month','DESC')
returns a DateQuerySet
of datetime.datetime
objects for each month that has Blog Entries. You can use this queryset in the template to create links to monthly archive pages.
这篇关于按年份,月份列出博客条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!