Which among the below is the most efficient method to get the
recent transactions?
1##using subquery
transactions = list(
Transaction.objects.filter(
pk__in=Subquery(
Transaction.objects.filter(user=self.request.user)
.order_by("-merchant", "-date_of_payment")
.distinct("merchant")
.values("pk")
)
).order_by("-date_of_payment")
2##using one query and sorting
transactions = (
Transaction.objects.filter(user=self.request.user)
.order_by("-merchant", "-date_of_payment")
.distinct("merchant")
)
recent_transactions = sorted(
transactions, key=operator.attrgetter("date_of_payment"), reverse=True
)
3##using two queries
transactions = Transaction.objects.filter(user=self.request.user).order_by("-merchant", "-date_of_payment").distinct("merchant")
recent_transactions = Transaction.objects.filter(id__in=transactions).order_by('-date_of_payment')