在Django中用最新的相关对象注释 [英] Annotate with latest related object in Django

查看:50
本文介绍了在Django中用最新的相关对象注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型对话和一个模型 Message .

I have a model Conversation and a model Message.

模型 Message 具有用于对话的外键,文本字段和日期字段.

The model Message has a foreign key to conversation, a text field, and a date field.

如何列出所有对话,并为每个对话获取最新消息和最新消息的日期?

How can I list all conversations and for each conversation get the most recent message and the date of the most recent message?

我想是这样的

Conversation.objects.annotate(last_message=Max('messages__date'))

但是它只会给我最新的日期.我希望 last_message 包含最后一条消息的文本和创建日期.也许我需要使用prefetch_related?

but it will only give me the latest date. I want last_message to contain both the text of the last message and the date it was created. Maybe I need to use prefetch_related?

推荐答案

从Django 1.11开始,您可以使用

Since Django 1.11, you could use Subqueries expressions:

latest_message = Subquery(Message.objects.filter(
    conversation_id=OuterRef("id"),
).order_by("-date").values('value')[:1])

conversations = Conversation.objects.annotate(
    latest_message=latest_message,
)

这篇关于在Django中用最新的相关对象注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆