Django: Sum up Counts in one query

时间:2017-04-24 17:17:53

标签: 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']
))

1 个答案:

答案 0 :(得分:2)

一种可能的解决方案:

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

<强>更新 如果你想获得元素列表:

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')