Annotate with latest related object in Django

徘徊边缘 提交于 2021-01-21 07:01:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!