[Answer]-Complex Ordering In Django with respect to related models

1👍

It’s way easier than that. You can use annotations to get the minimum creation date, then order on the annotations:

from django.db.models import Min, Q

conversations = Conversation.objects.filter(Q(sender=user) | Q(receiver=user)) \
                                    .annotate(min_date=Min('message__creation_date')) \
                                    .order_by('-min_date')
👤knbk

Leave a comment