本文介绍了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对象> >>> Meetup.objects.create(language ='python')< Meetup:Meetup对象> >>> Meetup.objects.create(language ='node')< Meetup:Meetup对象> >>> Meetup.objects.create(language ='node')< Meetup:Meetup对象> >>> Meetup.objects.annotate(latest_date = Max(date))。values(language,latest_date)。count() 4 我希望得到两个最新的Python和Node会议! 如何构建一个查询只抓取每种语言的最新聚会? PS。我使用MySQL作为后端。 解决方案将您的值注释之前的c $ c>子句。 来自聚集文档: 如果values()子句位于annotate()之前,则将使用values()子句中描述的分组来计算注释。 但是,如果annotate()子句位于values()子句的前面,则将在整个查询集上生成注释。在这种情况下,values()子句仅限制在输出中生成的字段。 所以这应该做到这一点: ('language')。annotate(latest_date = Max('date')) $ b Meetup.objects.values code> 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()4I 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. 解决方案 Put your values clause before the annotate.From the 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.So this should do it:Meetup.objects.values('language').annotate(latest_date=Max('date')) 这篇关于Django ORM - 获取组的最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-11 08:21