steerr
steerr

Reputation: 150

Ordering a list of querysets by latest record

I'd like to implement a private messaging function in Django, where a member can see his/her messages in one page, separated as conversations.

The conversation with the most recent message sent or received by the member should appear on top.

What I tried:

all_messages = Message.objects.filter(Q(sender=member) | Q(receiver=member))
other_members = all_messages.values_list("sender", flat=True).distinct()
conversations = []
for sender in other_members:
    if sender == member.id:
        try:        
            conversation = all_messages.filter(sender=member).exclude(receiver__in=other_members)
            conversations.append(conversation)
        except:
            continue
    else:
        conversation = all_messages.filter(Q(sender=sender, receiver=member) | Q(receiver=sender, sender=member))
        conversations.append(conversation)

The problem here is that when the member receives a new message, related conversation goes up; but when he sends a new message, conversation order doesn't change.

To sum up, how can I sort properly the conversations by the most recent last message in them?

Thanks!

Upvotes: 0

Views: 50

Answers (1)

Dalvtor
Dalvtor

Reputation: 3286

What I would do is to have another model, Conversation, that has a ForeignKey to each user who is taking part in the conversation. The model would also have a DateTimeField, last_updated, which you can update every time a message belonging to that conversation is posted. That way you can sort the conversations by last_updated.

Of course you need to add a conversation ForeignKey to the Message model.

Upvotes: 1

Related Questions