1👍
✅
You can order by the cost and obtain the last one, so:
def metrics(request):
topcat = CostCat.objects.annotate(sum=Sum('cost__amount')).latest('sum')
return render(request, 'metrics.html', {'topcat': topcat})
or if it is possible that there are categories without a Cost
, you can use nulls_last=True
[Django-doc]:
from django.db.models import F
def metrics(request):
topcat = CostCat.objects.annotate(sum=Sum('cost__amount')).earliest(
F('sum').desc(nulls_last=True)
)
return render(request, 'metrics.html', {'topcat': topcat})
Source:stackexchange.com