1👍
The most effective way is probably to work with a Subquery
expressions [Django-doc]:
from django.db.models import OuterRef, Subquery, Sum
def get_queryset(self, request, *args, **kwargs):
queryset = super().get_queryset(request, *args, **kwargs).annotate(
payment_amount=Subquery(
Payment.objects.filter(user=OuterRef('pk')).values('user').annotate(
total=Sum('amount')
).values('total').order_by('user')[:1]
),
payment_count=Count('payment__subpayment', distinct=True),
payment_sum=Subquery(
SubPayment.objects.filter(payment__user=OuterRef('pk')).values('payment__user').annotate(
total=Sum('amount')
).values('total').order_by('payment__user')[:1]
)
)
return queryset
Source:stackexchange.com