想象一下,我们有Django ORM模型Meetup,其定义如下:
class Meetup(models.Model): language = models.CharField() date = models.DateField(auto_now=True)
我想为每种语言取一个最新的聚会.
看起来你可以使用Django Aggregates来简化这种查找:
Meetup.objects.annotate(latest_date=Max("date")).values("language","latest_date")
在我看来,这应该取得每种语言的“最新”聚会.但事实并非如此:
>>> 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
我期望得到两个最新的Python和Node聚会!
PS.我使用MysqL作为我的后端.
解决方法
将您的values子句放在注释之前.
If the values() clause precedes the annotate(),the annotation will be computed using the grouping described by the values() clause.
However,if the annotate() clause precedes the values() clause,the annotations will be generated over the entire query set. In this case,the values() clause only constrains the fields that are generated on output.
所以这应该这样做:
Meetup.objects.values('language').annotate(latest_date=Max('date'))