Reputation: 53
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
Reputation: 476813
You can order the Chat
objects by the last (maximum) timestamp
of the related Message
s with:
from django.db.models import Max
Chat.objects.annotate(
last_message=Max('messages__timestamp')
).order_by('-last_message')
Upvotes: 1