How can I group objects by their date in Django?
I'm trying to select all objects in the articles table, and have them gro开发者_运维知识库uped by their date. I'm thinking it would look similar to this:
articles = Article.objects.filter(pub_date__lte=datetime.date.today()).group_by(pub_date.day)
articles = {'2010-01-01': (articleA, articleB, articleC...),
'2010-01-02': (article1, article2, article3...)...}
Here's a working example of ignacio's suggestion to use itertools.groupby
.
class Article(object):
def __init__(self, pub_date):
self.pub_date = pub_date
if __name__ == '__main__':
from datetime import date
import itertools
import operator
# You'll use your Article query here instead:
# a_list = Article.objects.filter(pub_date__lte = date.today())
a_list = [
Article(date(2010, 1, 2)),
Article(date(2010, 2, 3)),
Article(date(2010, 1, 2)),
Article(date(2011, 3, 2)),
]
keyfunc = operator.attrgetter('pub_date')
a_list = sorted(a_list, key = keyfunc)
group_list = [{ k.strftime('%Y-%m-%d') : list(g)}
for k, g in itertools.groupby(a_list, keyfunc)]
print group_list
Output:
[{'2010-01-02': [<__main__.Article object at 0xb76c4fec>, <__main__.Article object at 0xb76c604c>]}, {'2010-02-03': [<__main__.Article object at 0xb76c602c>]}, {'2011-03-02': [<__main__.Article object at 0xb76c606c>]}]
itertools.groupby()
MAybe you should do it at template level? If so you only need this : regroup tempalte tag
精彩评论