Django/Python: How to group queryset results by date?
Question: I have a model for image uploads, that looks something like this:

    
    
    from django.db import models
    from django.contrib.auth.models import User
    import datetime
    
    class ImageItem(models.Model):
        user = models.ForeignKey(User)
        upload_date = models.DateTimeField(auto_now_add = True)
        last_modified = models.DateTimeField(auto_now = True)
        original_img = models.ImageField(upload_to = img_get_file_path)
    

I want to query all instances of ImageItem that belong to a particular user,
and group them according to _date uploaded_. For example, for some user, I
want a group for April 9 2013, another for April 12 2013, etc. (assuming that
they uploaded one or more images on those dates).

I'm thinking I run a simple query, like,

    
    
    joes_images = ImageItem.objects.filter(user__username='joe')
    

**But then how could I group them by day published?** (assuming he did not
publish every day, only on some days)

The function would have to return all the groups of images.


Answer: why don't you do as following?

    
    
    joes_images = ImageItem.objects.filter(user__username='joe')  # your code
    upload_dates = set([(i.year, i.month, i.day) for i in joes_images])  # set of upload_date
    joes_images_separated = dict([(d, []) for d in upload_dates])
    for d in upload_dates:
        for i in joes_images:
            if (i.year, i.month, i.day) == d:
                joes_images_separated[d].append(i)
    

Here, `upload_dates` is a set of dates in `joes_images` and you get
`joes_images_separated` as a dict (keys are dates, values are lists of
`joes_images` for each date).

I'm sorry for a little dirty code. I think this works. for your information.

