Imagine we have the Django ORM model Meetup
with the following definition:
class Meetup(models.Model):
language = models.CharField()
date = models.DateField(auto_now=True)
I'd like to fetch the latest meetup for each language.
It would seem you could use Django Aggregates to make this lookup easy:
Meetup.objects.annotate(latest_date=Max("date")).values("language", "latest_date")
In my mind this should fetch the "latest" meetup for each language. But that's not the case:
>>> Meetup.objects.create(language='python')
<Meetup: Meetup object>
>>> Meetup.objects.create(language='python')
<Meetup: Meetup object>
>>> Meetup.objects.create(language='node')
<Meetup: Meetup object>
>>> Meetup.objects.create(language='node')
<Meetup: Meetup object>
>>> Meetup.objects.annotate(latest_date=Max("date")).values("language", "latest_date").count()
4
I expected to get just the two latest Python and Node meetups!
How can I construct a query that will fetch only the latest meetups for each language?
PS. I'm using MySQL as my backend.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…