damon
damon

Reputation: 15128

How can I group objects by their date in Django?

I'm trying to select all objects in the articles table, and have them grouped 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...)...}

Upvotes: 1

Views: 748

Answers (3)

Sam Dolan
Sam Dolan

Reputation: 32532

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>]}]

Upvotes: 4

Aldarund
Aldarund

Reputation: 17621

MAybe you should do it at template level? If so you only need this : regroup tempalte tag

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798636

itertools.groupby()

Upvotes: 2

Related Questions