我有一个非常简单的查询,我想通过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来保持一致.

谢谢

推荐答案

试试这个:

Rating.objects.filter(attribute__in=attributes) \
    .values('location') \
    .annotate(score = Sum('score')) \
    .order_by('-score')

Django相关问答推荐

Django如何在没有ctrl点击的情况下允许多选

如何使用具有某些权限的 Django 组的转储数据和加载数据?

AttributeError:模块rest_framework.serializers在 Swagger 中的 Django 中没有属性NullBooleanField

为什么我的搜索功能返回错误相关字段查找无效:​​类别

遍历django模板中的外键相关表

Django ORM 和锁定表

如何在终端中切换 Python 版本?

UnicodeDecodeError:asciicodec can't decode byte 0xe0 in position 0: ordinal not in range(128)

django post_save 更新信号

清理提交的表单数据中的 HTML

UnicodeEncodeError:ascii编解码器无法编码字符

django Datefield 到 Unix 时间戳

Django unique=True 不工作

Django:如何将数据保存到 ManyToManyField?

将 jQuery 脚本添加到 Django 管理界面

Django Rest 框架 ImageField

django sql 查询如何使用不区分大小写的同时包含?

使用 request.user 的 Django 和中间件始终是匿名的

想要在 Django 测试中禁用信号

django/文件上传权限