0

I have a message database and it has senderid, receiverid, message and date. Now I would like to get list of users whom I have recently messaged with one latest message (sent or received) per person. How can I get just a single row of message per person.

I tried but this game me all the messages between two users, I just want the latest message.

querySet=MessageModel.objects.filter(
            Q(sUser=self.request.user) |     
            Q(rUser=self.request.user)
        )
        return querySet

but this game me all the messages between two users, I just want the latest message.

simplegalaxy
  • 135
  • 1
  • 2
  • 6

1 Answers1

0

You can sort the QuerySet and then just grab the first item in the list.

querySet = MessageModel.objects.filter(
    Q(sUser=self.request.user) |     
    Q(rUser=self.request.user)
).order_by('-date')[0]

.order_by(...) sorts a QuerySet based on a specific field (ascending order is implied). By using .order_by('-date'), the -date denotes we want a descending order, rather than the default ascending order. We can then just grab the first item in our QuerySet with [0].

Further reading: Good ways to sort a queryset? - Django

wcarhart
  • 2,685
  • 1
  • 23
  • 44