想象一下,我们有一个Meetup
具有以下定义的 Django ORM 模型:
class Meetup(models.Model):
language = models.CharField()
speaker = models.CharField()
date = models.DateField(auto_now=True)
我想使用单个查询来获取每种语言的最新事件的语言、演讲者和日期。
>>> Meetup.objects.create(language='python', speaker='mike')
<Meetup: Meetup object>
>>> Meetup.objects.create(language='python', speaker='ryan')
<Meetup: Meetup object>
>>> Meetup.objects.create(language='node', speaker='noah')
<Meetup: Meetup object>
>>> Meetup.objects.create(language='node', speaker='shawn')
<Meetup: Meetup object>
>>> Meetup.objects.values("language").annotate(latest_date=models.Max("date")).values("language", "speaker", "latest_date")
[
{'speaker': u'mike', 'language': u'python', 'latest_date': ...},
{'speaker': u'ryan', 'language': u'python', 'latest_date': ...},
{'speaker': u'noah', 'language': u'node', 'latest_date': ...},
{'speaker': u'shawn', 'language': u'node', 'latest_date': ...},
]
哦!我们收到了最新的活动,但分组错误!
似乎我需要一种方法来GROUP BY
但在一language
组SELECT
不同的字段上?
更新- 这种查询似乎很容易用 SQL 表达:
SELECT language, speaker, MAX(date)
FROM app_meetup
GROUP BY language;
我很想在不使用 Django 的情况下做到这一点raw()
- 有可能吗?
更新 2 - 经过大量搜索,似乎有类似的问题:
更新 3 - 最后,在@danihp 的帮助下,您能做的最好的事情似乎是两个查询。我使用了以下方法:
# Abuse the fact that the latest Meetup always has a higher PK to build
# a ValuesList of the latest Meetups grouped by "language".
latest_meetup_pks = (Meetup.objects.values("language")
.annotate(latest_pk=Max("pk"))
.values_list("latest_pk", flat=True))
# Use a second query to grab those latest Meetups!
Meetup.objects.filter(pk__in=latest_meetup_pks)
这个问题是我上一个问题的后续: