1
votes

I have a private user to user messaging model. (Photographer is a ForeignKey to the Django User)

class Message(models.Model):
     sender = models.ForeignKey(Photographer)
     recipient = models.ForeignKey(Photographer, related_name= 'messagedby', blank=True)
     postTime = models.DateTimeField(auto_now_add=True, null=True, blank =True)
     message = models.CharField(max_length=500)

     def __unicode__(self):
          return self.message

As you can see, each message has a sender and a recipient. Both the sender and the recipient can view the same message.

I need to retrieve a distinct list of the latest messages for each pair of users.

Currently I can retrieve distinct pairs but it is returning more results than I want:

queryset = Message.objects.all().distinct('sender', 'recipient')

There are multiple messages coming through with the same pairs of users. For example,

John is the sender and Jane is the recipient.

In another returned message,

Jane is the sender and John is the recipient.

From this, I want to get only one of these two messages which is the latest one. How can I accomplish this?

1

1 Answers

-2
votes

You're looking for .distinct()

documentation