在 Django 中对日期进行分组 [英] Grouping dates in Django

查看:30
本文介绍了在 Django 中对日期进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与这篇文章几乎一模一样,除了我使用 Python 和 Django 而不是 PHP.

My question is almost exactly the same as this post, except that I'm using Python and Django instead of PHP.

任务是:

id date  
1 2009-01-01 10:15:23  
2 2009-01-01 13:21:29  
3 2009-01-02 01:03:13  
4 2009-01-03 12:20:19  
5 2009-01-03 13:01:06 

和输出:

2009-01-01  
1  
2   
2009-01-02  
3  
2009-01-03  
4  
5  

我可以通过遍历排序的日期并将 HTML 输出到我的 python 视图文件中的字符串中来手动将某些东西组合在一起,但我想知道:是否有更好的方法使用 Django 模板或漂亮的 Python 功能?

I can manually hack something together by looping through the sorted dates and outputting HTML into a string in my python view file, but I'm wondering: is there's a better way using a Django template or a nifty Python feature?

推荐答案

您可以使用 regroupdate 模板标签来解决这个问题.

You can solve this with the regroup and date templatetags.

{% regroup object_list by start_date|date:"Y-m-d" as objects_by_day %}
{% for d in objects_by_day %}
### DO SOMETHING HERE
{% endfor %}

这篇关于在 Django 中对日期进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆