Samy van Stokkum
Samy van Stokkum

Reputation: 53

Order objects that contain a many-to-many field that need to be ordered beforehand in Django

I've these two models:

class Message(models.Model):
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)

class Chat(models.Model):
    title = models.CharField(max_length=255)
    messages = models.ManyToManyField('Message')

How do I order the chats by the last send message in each chat?

Upvotes: 0

Views: 26

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

You can order the Chat objects by the last (maximum) timestamp of the related Messages with:

from django.db.models import Max

Chat.objects.annotate(
    last_message=Max('messages__timestamp')
).order_by('-last_message')

Upvotes: 1

Related Questions