【发布时间】:2011-09-06 13:25:44
【问题描述】:
我有一个带有日期时间字段的模型。我想得到一个包含三列的表,分别是年、月和时间跨度中的项目数。而且我还想从最新到最旧订购它们。我想要得到的是这样的:
2011 August 4
2011 March 7
你建议我应该怎么做?
编辑
我最终做了这样的事情,但我不确定这是否是最好的方法。
query_set = Post.objects.all()
years = query_set.dates("pub_date","year")
date_hierarchy = {}
for year in years:
date_hierarchy[year] = {}
months = query_set.filter(pub_date__year=year.year).dates("pub_date","month")
for month in months:
date_hierarchy[year][month] = query_set.filter(pub_date__year=month.year,pub_date__month=month.month).count()
然后,在模板中:
{% for year, month_dict in date_hierarchy.items %}
{% for month,post_count in month_dict.items %}
<li><a href="{% url arsiv_month month.year month.month %}">{{ month|date:"Y E" }} [{{ post_count }}]</a></li>
{% endfor %}
{% endfor %}
【问题讨论】:
-
Django 和 Python 都允许您将日期拆分成它们的部分,所以也许您实际上并不需要 3 列而可以只使用 1。您要解决什么问题?跨度>
-
我有博客文章,我正在尝试在主页中创建一个存档部分,我将在其中显示逐月链接,在链接文本中,我将在括号中给出该月的帖子数量。
标签: django