sql – Django ORM – 获取组的最新记录

前端之家收集整理的这篇文章主要介绍了sql – Django ORM – 获取组的最新记录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
想象一下,我们有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子句放在注释之前.

aggregation docs

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'))
原文链接:https://www.f2er.com/mssql/83573.html

猜你在找的MsSQL相关文章