Annotate with the last related object in Django

I have a model Conversationand a model Message.

The model Messagehas a foreign key for 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 last message?

I think something like

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

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

+7
source share
1 answer

You can do this with prefetch_relatedand queryset. Sort of:

Conversation.objects.prefetch_related(
    Prefetch('messages'),
    queryset=Message.objects.order_by('date').first()
)
-2
source

All Articles