Assume we have table Discussion and a table Message. Message has columns: id, created_at, text, author, discussion_id. Discussion has columns: id, created_at, participant1, participant2. For a given user, how can you create a queryset of the discussions sorted in their recent-ness. The recent-ness of a discussion is defined by the maximum created_at of the discussion of the latest message in this discussion.
Now, is there a way to do this WITHOUT SUBQUERIES and such that I can access the latest_message as if it was a one-to-one model of discussion (which means that I could access the message text by doing: discussion.latest_message.text AND NOT discussion.latest_message_text [which wouldve been annotated to the request]).
Here is what I came up with so far:
Discussion.objects.annotate(
latest_message_date=Max('message__created_at'), # Using reverse relation from Discussion to Message
latest_message_text=Max('message__text'), # Somehow retrieves the text of the latest_message
latest_message_author=Max('message__author__username')
).annotate(
recent_date=Greatest(
'created_at',
F('latest_message_date')
)
).filter(
Q(participant1=user) | Q(participant2=user)
).order_by('-recent_date')
It works well but I was wondering if there was a way to somehow assign latest_message to the model of message instead of annotating every single field. I can survive without it, its just good to know.