使用 Django ORM 按日期对对象进行排序和分组
我有一个带有日期字段的文章模型。我想查询所有 Article 对象,并返回每个不同年份的数据类型,然后返回其中每个不同的月份。
例如
<代码> 档案={ 2009: {12, [, , ...], 11: [...]}, 2008:{12,[...],11:[...]}, }
这可能吗?
I have an Article model which has a date field. I want to query against all Article objects, and have a datatype returned with each distinct year, and then each distinct month within that.
for instance
archives = {
2009: {12, [, , ...], 11: [...]},
2008: {12, [...], 11: [...]},
}
is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这类问题似乎经常出现。最简单的解决方案是循环访问数据并按年份和月份对对象进行分组。您可以在视图中手动执行此操作或使用 regroup 在您的模板中。这实际上取决于您想对数据做什么。
如果在应用程序中按年和月对档案进行分组是很常见的事情,那么您可能需要考虑创建在 save() 上填充的年和月字段。
手动它可能是这样的:
或者使用 regroup(未经测试):
我个人会尝试将逻辑放在视图中而不是模板中。
以下是一些相关帖子:
This sort of question seems to come up fairly often. The easiest solution is to loop through the data and group the objects by year and month. You can do this by hand in the view or using regroup in your template. It really depends on what you want to do with the data.
If grouping Archives by year and month is a very common thing for you to do in your application, you might want to consider creating a year and month field that you populate on save().
By hand it could be something like this:
Or pushing all the grouping logic into the template using regroup (untested):
I would personally try to put the logic in the view instead of in the template.
Here are a few related posts:
没有快速的解决方案,但您可以检查 dates() 方法。
There is no quick solution, but you may check dates() method.