Search code examples
pythondjangogroup-bypython-itertools

django, group model by days


I have models.py with:

class Game(models.Model):
    date = models.DateTimeField()

I want to have a function that returns all games grouped by days. Result should be a dict with keys: 'day' and 'games' (list of games for the day). I do it in such way:

from itertools import groupby

def get_games_grouped_by_days():
    def get_day(obj):
        return obj.date.day
    games = Game.objects.all()
    grouped_games = []
    for day, games_in_day in groupby(games, key=get_day):
        grouped_games.append({
            'day': day,
            'games': list(games_in_day)
        })
    return grouped_games

This function works fine, but I would like to know if there is a more query-way to do such group thing.


Solution

  • what about this:

    query = Game.objects.all().query
    query.group_by = ['date']
    results = QuerySet(query=query, model=Game)
    

    Then you can iterate on results, and get the day and game from each item.