Django: Distinct foreign keys

后端 未结 4 759
名媛妹妹
名媛妹妹 2021-01-17 10:02
class Log:
 project = ForeignKey(Project)
 msg = CharField(...)
 date = DateField(...)

I want to select the four most recent Log entries where each

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 10:35

    You need two querysets. The good thing is it still results in a single trip to the database (though there is a subquery involved).

    latest_ids_per_project = Log.objects.values_list(
        'project').annotate(latest=Max('date')).order_by(
        '-latest').values_list('project')
    
    log_objects = Log.objects.filter(
         id__in=latest_ids_per_project[:4]).order_by('-date')
    

    This looks a bit convoluted, but it actually results in a surprisingly compact query:

    SELECT "log"."id",
           "log"."project_id",
           "log"."msg"
           "log"."date"
    FROM "log"
    WHERE "log"."id" IN
        (SELECT U0."id"
         FROM "log" U0
         GROUP BY U0."project_id"
         ORDER BY MAX(U0."date") DESC
         LIMIT 4)
    ORDER BY "log"."date" DESC
    

提交回复
热议问题