2

I want to create a queryset which retrieve users efficiently ordered by the create date of the last Message they sent OR received (like most of the chat interfaces do). I am using Django Private Chat, which uses this simple model for messages.

I simply don't know how writing the order_by statement considering the previous model. Maybe annotate, Subquery or other query expressions would be convenient in this case.

users = User.objects.filter(
    username__icontains=user,
    id__in=request.user.followers
).order_by( ????? )
markwalker_
  • 12,078
  • 7
  • 62
  • 99

1 Answers1

0

You should be able to do this using annotate and something like;

from django.db.models import Max

users = User.objects.filter(
    username__icontains=user,
    id__in=request.user.followers
).annotate(
    last_message=Max('messages_created')
).order_by('-last_message')

The Max function takes the related name from the Message model, found here, then the created timestamp of that model.

markwalker_
  • 12,078
  • 7
  • 62
  • 99