【问题标题】:Django ORM get latest item for each groupDjango ORM 获取每个组的最新项目
【发布时间】:2019-10-11 13:05:15
【问题描述】:

我正在使用 Django 2.2.1 和 MariaDB 10.3.15。

我有这个模型:

class Hose(models.Model):
    description = models.CharField(blank=True, max_length=250)
    number = models.IntegerField(unique=True)

class HoseHistory(models.Model):
    class Meta:
        unique_together = (("date", "hose", "hose_event"),)

    date = models.DateTimeField()
    description = models.CharField(blank=True, max_length=250)
    hose = models.ForeignKey(Hose, on_delete=models.CASCADE)
    hose_event = models.ForeignKey(HoseEvent, on_delete=models.CASCADE)

现在我想获取 Hose Table 的所有条目的列表,如果有的话,最新的 HoseHistory 行。

结果集应如下所示:

| Hose.description | Hose.number | HoseHistory.date | HoseHistory.description |
===============================================================================
|    Example A     |      1      |    2019-01-09    |         Event A         |
|    Example B     |      2      |       NULL       |          NULL           |

所以详细来说,Django 应该创建一个 SQL 查询,它选择 Tabele Hose,LEFT JOINs 表 HoseHistory,然后按 Hose.number 分组,然后在 HoseHistory.date 上的所有 MAX。

我试过例如:

Hose.objects.values("number").annotate(max_date=Max("hosehistory__date")).order_by("hosehistory__date")

但问题是,使用此策略我只有列 max_datenumber,如果我添加更多列,这些列将添加到 GROUP BY 语句中,并且此查询将不起作用。

【问题讨论】:

    标签: python django orm


    【解决方案1】:

    你可以在模型中添加一个方法

    def latest_history(self):
        return HoseHistory.objects.filter(hose=self).order_by('-date').first()
    

    并在您的模板中调用:{{ hose.latest_history }} 如果存在最新历史记录

    【讨论】:

    • 目前我有一个解决方案可以做到这一点,但是对于较大的数据集(在我的情况下大约有 1000 根软管),这是非常低效的。
    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 2013-11-24
    • 2017-04-11
    • 2018-06-14
    • 2013-07-27
    • 2018-08-28
    • 2020-02-22
    相关资源
    最近更新 更多