Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Aggregation: highest sum in categories

Hy Guys

I was wondering how I can get the highest sum of one category.

So i have a model with my categories and a model with my costs which contains a cost category.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My models.py

from django.db import models

class CostCat(models.Model):
    name = models.CharField(max_length=50, default=None, null=True, blank=True)


class Cost(models.Model):
    name = models.CharField(max_length=50, default=None, null=True, blank=True)
    cost_category = models.ForeignKey(CostCat, on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=12, decimal_places=2,null=True, blank=True)

The result should be that I can show the category with the highest sum of costs.

I have been stuck on that for hours now. The closest i got was with my tests as shown below.

I can print out all the sums and its respective category but now I now need to find out how to get the category and the value of the highest sum. And i’m really in a spiral right now.

views.py

def metrics(request):

    tests = CostCat.objects.annotate(sum=Sum('cost__amount'))

    for test in tests:

        print(test, test.sum)

    return render(request, 'metrics.html', "topcostcat":test, "topcostcatsum":test.sum )


Much appreciated if you could me a bit out!

Thanks in advance

>Solution :

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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading