In django, is there a way to directly annotate a query with a related object in single query?

前端 未结 3 542
南旧
南旧 2021-02-05 18:02

Consider this query:

query = Novel.objects.< ...some filtering... >.annotate(
    latest_chapter_id=Max(\"volume__chapter__id\")
)

Actual

3条回答
  •  梦毁少年i
    2021-02-05 18:24

    Yes, it's possible.

    To get a queryset containing all Chapters which are the last in their Novels, simply do:

    from django.db.models.expressions import F
    from django.db.models.aggregates import Max
    
    Chapters.objects.annotate(last_chapter_pk=Max('novel__chapter__pk')
        ).filter(pk=F('last_chapter_pk'))
    

    Tested on Django 1.7.

提交回复
热议问题