【发布时间】:2019-07-12 23:03:19
【问题描述】:
有两种型号:
class Article(..:
locations = ManyToMany('Location'...,related_name='articles')
class Location(...):
...
我正在寻找一种方法来获取任何相关集 Article.locations 中的位置出现次数
例如:
- Article1 - 米兰、维也纳、巴黎
- 第 2 条 - 米兰、巴黎
- 第 3 条 - 巴黎
- 文章 - 迪拜
结果是:
巴黎 - 3,米兰 - 2,维也纳 - 1,迪拜 -1
我以这个结尾:
Location.objects.all().annotate(Count(?))
一两个Queries可以做到吗?我想避免使用循环。
此外,我只想考虑Articles 的子集(过滤查询集)。
【问题讨论】:
标签: python django postgresql django-orm