gpt4 book ai didi

python - Django:在一个查询中汇总计数

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:24 25 4
gpt4 key购买 nike

我有一个元素列表,我想根据相关多对多元素的数量对其进行排名。我认为汇总这些源元素的计数是正确的方法,但我还没有找到解决方案。

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

最佳答案

一种可能的解决方案:

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

关于python - Django:在一个查询中汇总计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com