3👍
✅
I think I’ve found the answer.
qs = User.objects.annotate(
last_message_time=Max("messages__created_at"),
last_message_message=Subquery(
Chat.objects.filter(user=OuterRef("id")).order_by("-created_at").values("message")[:1]
)
).order_by("-last_message_time")
I got help from this article on this issue!
https://medium.com/@hansonkd/the-dramatic-benefits-of-django-subqueries-and-annotations-4195e0dafb16
1👍
I don’t think you can do it easily with one query. This looks like exactly what you are looking for.
You can either write a custom raw SQL query to get what you want or do something not efficient like that in two steps:
qs = User.objects.annotate(
last_message_time=Max("messages__created_at"),
).order_by("-last_message_time")
for user in qs:
user.last_message = Chat.objects.get(user=user, created_at=user.last_message_time)
Source:stackexchange.com