Most efficient method for fetching data

12 views
Skip to first unread message

Dhanya Aleena

unread,
Nov 3, 2022, 10:32:28 PM11/3/22
to Django users
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')
Reply all
Reply to author
Forward
0 new messages