我有一个非常简单的查询,我想通过ORM进行,但我想不出来..
我有三种型号:
位置(地点)、属性(地点可能具有的属性)和评级(也包含分数字段的M2M直通模型)
我想挑选一些重要的属性,并能够根据这些属性对我的位置进行排名——即所有选定属性的总分越高=越好.
我可以使用以下SQL来获得我想要的:
select location_id, sum(score)
from locations_rating
where attribute_id in (1,2,3)
group by location_id order by sum desc;
哪一个返回
location_id | sum
-------------+-----
21 | 12
3 | 11
我能与ORM取得的最接近的结果是:
Rating.objects.filter(
attribute__in=attributes).annotate(
acount=Count('location')).aggregate(Sum('score'))
哪一个返回
{'score__sum': 23}
即所有的总和,而不是按位置分组.
有什么办法绕过这件事吗?我可以手动执行SQL,但更愿意通过ORM来保持一致.
谢谢