tags:

views:

76

answers:

3

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...)...}
+2  A: 

itertools.groupby()

Ignacio Vazquez-Abrams
any more information on this?
What more information is required? It takes an iterable, and a function to extract the grouping key from the elements of the iterable.
Ignacio Vazquez-Abrams
My guess is that the OP wants the ORM to issue a GROUP BY SQL query, in that case this won't help him.
Bastien Léonard
@Bastien: Did you read the question, and look at the example provided?
Ignacio Vazquez-Abrams
A: 

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

Aldarund
+3  A: 

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>]}]
sdolan
`keyfunc = operator.attrgetter('pub_date')`
Ignacio Vazquez-Abrams
@Ignacio - Thanks, I've updated my sample code. Any idea (roughly) how much faster this is than using lambda?
sdolan
It probably isn't.
Ignacio Vazquez-Abrams
this worked perfectly. i did replace the keyfunc with a lambda. thanks for the help.