Aamu
Aamu

Reputation: 3611

django - query a class by the latest created object of another class

How to query so as to get the thread in the order that has the latest message.

Edit:

Eg:

  1. Suppose, A sent a message to B, (Thread_1). Here Thread_1 is at the top.
  2. Now, C sent a message to B, (Thread_2). Here Thread_2 is at the top and Thread_1 is below it.
  3. Again, A sent a message to B, (Thread_1). Here again, Thread_1 is at the top and Thread_2 is below it.

models.py:

class Thread(models.Model):
    user = models.ManyToManyField(User)

class Message(models.Model):
    thread = models.ForeignKey(Thread)
    sent_date = models.DateTimeField(default=datetime.now)
    body = models.TextField()
    user = models.ForeignKey(User)

Upvotes: 2

Views: 54

Answers (1)

mariodev
mariodev

Reputation: 15604

Try this:

from django.db.models import Max

Thread.objects.annotate(max_sent_date=Max('message_set__sent_date')).order_by('-max_sent_date')

Upvotes: 2

Related Questions