1

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.

sgarza62
  • 5,998
  • 8
  • 49
  • 69
  • 1
    Have you read this question? http://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django – Henrik Andersson Apr 13 '13 at 05:01
  • No, I hadn't, and that definitely solves the first half of my question. Here, the `upload_date` field is a datetime.datetime object, which means no two upload_date values are the same. I would like to group only according to date, not time. How would I do that? – sgarza62 Apr 13 '13 at 05:29
  • I think you have to use `.extra()` for that, you can't `.order_by()` on a datetimefield unfortunately :( – Henrik Andersson Apr 13 '13 at 05:31
  • You could however convert it to a DateTimeField instead and be done with it. Ie. have one field for grouping on and one field for doing whatever else on. (This is a bit superflous but it'd work) – Henrik Andersson Apr 13 '13 at 05:37
  • Ref http://stackoverflow.com/a/2283913/165603 , you could do it in `extra` by typing cast datetime to date. If applicable, writing a SQL in `raw()` is more clear. – okm Apr 13 '13 at 10:25

1 Answers1

4

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.

gh640
  • 164
  • 2
  • 6
  • You do not need 2 for loops. Get rid of `for d in upload_dates:` and the if statement and just construct the date key `d` for every image in `joes_images` – roob Nov 11 '16 at 00:01