MiniGunnR
MiniGunnR

Reputation: 5800

How to get latest value of a field on a related model in Django?

I have the following models:

class Timestamped(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Thread(Timestamped):
    user1 = models.ForeignKey(User, related_name='user1')
    user2 = models.ForeignKey(User, related_name='user2')

class Message(Timestamped):
    thread = models.ForeignKey(Thread)
    text = models.CharField(max_length=255)
    sender = models.ForeignKey(User)

I have a QuerySet to get all threads, but I also want to display the latest message for each thread while I loop over them.

I have come up with the following to show the latest Timestamp for the message.

threads = Thread.objects.filter(Q(user1=request.user) | Q(user2=request.user))\
            .annotate(latest_msg=Max('message__modified')).order_by('-latest_msg')

How can I show the message text?

Upvotes: 1

Views: 2201

Answers (1)

Exprator
Exprator

Reputation: 27543

threads = Thread.objects.filter(
            Q(user1=request.user) | Q(user2=request.user)
          ).annotate(
            latest_msg=Max('message__modified')
          ).values(
            'message__text',
            'fields you want to fetch'
          ).order_by('-latest_msg')[:1]

Upvotes: 2

Related Questions