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'))

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...