I'm trying to filter for the first (or last) n Message objects which match a certain filter. Right now I need to filter for all matches then slice.
def get(self, request, chat_id, n):
last_n_messages = Message.objects.filter(chat=chat_id).order_by('-id')[:n]
last_n_sorted = reversed(last_n_messages)
serializer = MessageSerializer(last_n_sorted, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
This is clearly not efficient. Is there a way to get the first (or last) n items without exhaustively loading every match?