Django: Distinct foreign keys

后端 未结 4 758
名媛妹妹
名媛妹妹 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条回答
  •  -上瘾入骨i
    2021-01-17 10:47

    Queries don't work like that - either in Django's ORM or in the underlying SQL. If you want to get unique IDs, you can only query for the ID. So you'll need to do two queries to get the actual Log entries. Something like:

    id_list = Log.objects.order_by('-date').values_list('project_id').distinct()[:4]
    entries = Log.objects.filter(id__in=id_list)
    

提交回复
热议问题