Django ORM - Get latest record for group

后端 未结 1 860
眼角桃花
眼角桃花 2020-12-10 06:42

Imagine we have the Django ORM model Meetup with the following definition:

class Meetup(models.Model):
    language = models.CharField()
    dat         


        
1条回答
  •  有刺的猬
    2020-12-10 06:58

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

    0 讨论(0)
提交回复
热议问题