【问题标题】:Date hiearchy of items in djangodjango中项目的日期层次结构
【发布时间】: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


【解决方案1】:

看看 SQL 的GROUP BY 子句。 django 支持这一点。例如:Django annotate groupings by month(我链接的问题中的第二个响应似乎比接受的答案更便携)。

【讨论】:

  • 我不是要获取订购日期的模型,而是要获取带有项目计数的订购日期。我在原始帖子中添加了更多信息。
  • 您提供的链接看起来像是答案,但是,我对此一无所知。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
相关资源
最近更新 更多