[Answered ]-How to sort by field using ForeignKey

1👍

The reason this happens is because it will make a LEFT OUTER JOIN on Message, and thus for each Message, return the Room once, and thus the same room can occur multiple times.

You can annotate with the largest timestamp, so:

from django.db.models import Max

Room.objects.alias(
    latest_message=Max('message_room__timestamp')
).order_by('latest_message')

Leave a comment