Django Distinct和外键过滤查询

时间:2017-09-22 15:03:35

标签: django django-views django-orm

我发现了关于这个问题的问题,但没有正常工作的答案,所以任何帮助都表示赞赏:)

我想显示每个客户制作的最新记录列表。 记录是一个模型,它将客户端作为字段。 客户端是用户的ForeignKey。

例如

#Initially:

Client3 --- Record6
Client2 --- Record5
Client2 --- Record4
Client1 --- Record3
Client1 --- Record2
Client1 --- Record1

#Wanted: we only keep one Record per Client, the lastest one.

Client3 --- Record6
Client2 --- Record5
Client1 --- Record3

这就是我的尝试:

def LastRecordPerClient(request):
    id_list = Record.objects.order_by('-date').values_list('client__id').distinct()
    records = Record.objects.filter(id__in=id_list)
    return (request, 'records/record_list.html', {"records": records})

这是我在我的shell中得到的:

<QuerySet []>

有什么想法吗?

编辑:找到解决方案

我找到了这个解决方案:

class LastestListView(ListView):
    context_object_name = 'records'
    model = models.Record
    ordering = ['-date']
    paginate_by = 10

    def get_queryset(self):
        return self.model.objects.filter(pk__in=
        Record.objects.order_by('-date').values('client__id').annotate(
            max_id=Max('id')).values('max_id'))

1 个答案:

答案 0 :(得分:-1)

为什么不Record.objects.filter(client_id=<client_id>).order_by('-date').last()

我知道,那么最好的方式可能是cached_property

models.py:

class Client(models.model):
    name = models.CharField(...)
    ....
    @cached_property
    def latest_record = Record.objects.filter(client=self).order_by('-date').last()

然后在你看来:

clients = Client.objects.all().prefetch_related('record')

for client in clients:
   print(client.name)
   print(client.latest_record.date)

这将为您提供问题中要求的输出。