最近在用 Django 做一个个人 Blog,想实现一个文章归档功能,效果像这样:
就是首页递减显示文章发表年份,点击该年份展开显示该年下的月份。
我目前的实现思路是这样的:
首先获取全部文章的发表时间(精确到月,已去重):
date_list = Article.objects.datetimes('created_time', 'month')
然后把时间列表放到一个字典里,键是年份,值为月份列表:
date_dict = defaultdict(list) for d in date_list: print(type(d.year)) print(type(d.month)) date_dict[d.year].append(d.month) return dict(date_dict) # 模板不支持defaultdict
在模板中循环出来:
{% for year,month_list in d.items %} {{year}}
{% for month in month_list %}
{{month}}
能够实现部分需求,但是总觉得不优雅,其次是由于字典是无序的,可能导致显示的并非按照时间递减排序,如果要保持有序可能还得将字典改成二重列表,感觉更不优雅了。
有什么更加优雅一些的实现方法么?或者一些比较好的实践方法介绍。
I want the dictionary to be available in order OrderedDict
In fact, you don’t even need OrderedDict. Just sort the keys directly. Using the native MultiValueDict will be more elegant
Come and get the full version
Thank you everyone, it has been solved perfectly now. Django has already had solutions to this type of problem. Template tags have regroup, which is designed to solve this problem. Dictionary sorting also has the oderdict template filter.