问题
I have a model Conversation
and a model 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?
I guess it's something like
Conversation.objects.annotate(last_message=Max('messages__date'))
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?
回答1:
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,
)
回答2:
You can do it with prefetch_related
and a queryset
. Something like:
Conversation.objects.prefetch_related(
Prefetch('messages'),
queryset=Message.objects.order_by('date').first()
)
来源:https://stackoverflow.com/questions/30528268/annotate-with-latest-related-object-in-django