【问题标题】:Django/Python: How to group queryset results by date?Django/Python:如何按日期对查询集结果进行分组?
【发布时间】:2013-04-05 17:42:57
【问题描述】:

我有一个图片上传模型,看起来像这样:

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)

我想查询属于特定用户的所有 ImageItem 实例,并根据上传日期对它们进行分组。例如,对于某些用户,我想要 2013 年 4 月 9 日的群组,2013 年 4 月 12 日的群组等等(假设他们在这些日期上传了一张或多张图片)。

我想我运行一个简单的查询,比如,

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

但是我怎么能按发布日期对它们进行分组呢?(假设他不是每天都发布,只是在某些日子)

该函数必须返回所有图像组。

【问题讨论】:

  • 你读过这个问题吗? stackoverflow.com/questions/629551/…
  • 不,我没有,这绝对解决了我问题的前半部分。这里,upload_date 字段是一个 datetime.datetime 对象,这意味着没有两个 upload_date 值是相同的。我只想按日期分组,而不是按时间分组。我该怎么做?
  • 我认为你必须为此使用.extra(),不幸的是你不能在日期时间字段上使用.order_by() :(
  • 但是,您可以将其转换为 DateTimeField 并完成它。 IE。有一个用于分组的字段和一个用于执行其他操作的字段。 (这有点多余,但它会起作用)
  • Ref stackoverflow.com/a/2283913/165603 ,您可以在 extra 中输入 cast datetime to date 来完成。如果适用,在raw() 中写一条 SQL 会更清晰。

标签: python django datetime django-models


【解决方案1】:

你为什么不按照下面的做呢?

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)

这里,upload_datesjoes_images 中的一组日期,而joes_images_separated 是一个字典(键是日期,值是每个日期的joes_images 列表)。

抱歉,代码有点脏。我认为这行得通。供您参考。

【讨论】:

  • 您不需要 2 个 for 循环。去掉for d in upload_dates:和if语句,只为joes_images中的每个图像构造日期键d
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 2023-01-13
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-04-03
  • 1970-01-01
  • 2019-08-19
相关资源
最近更新 更多