Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Sum up Counts in one query

Tags:

python

django

I have a list of elements that i would like to rank according to the count of related manytomany elements. I think aggregating the counts of those source elements is the right way, but i haven't found a solution yet.

class Element(models.Model):
     Source1 = models.ManyToManyField(Source1)
     Source2 = models.ManyToManyField(Source2)
     Source3 = models.ManyToManyField(Source3)


Ranked = (Element.objects.all().aggregate(
         Ranked=Sum(F('Source1') + F('Source2') + F('Source3'), output_field=IntegerField)['Ranked']
))
like image 700
Merlin Schumacher Avatar asked Apr 24 '17 17:04

Merlin Schumacher


1 Answers

One possible solution:

agg_data = Element.objects.aggregate(total_source1=Count('Source1'), total_source2=Count('Source2'), total_source3=Count('Source3'))
total_count = sum(agg_data.values()) # this is value which you need

Update: If you want to get list of Element:

res = Element.objects.all().annotate(total_source1=Count('Source1'), total_source2=Count('Source2'), total_source3=Count('Source3'))
.annotate(total_count=F('total_source1') + F('total_source2') + F('total_source3')).order_by('-total_count')
like image 106
ittus Avatar answered Oct 21 '22 02:10

ittus