【发布时间】:2011-09-01 06:32:42
【问题描述】:
大家好,我有一个看起来像这样的模型:
class Interaction(DateAwareModel, UserAwareModel):
page = models.ForeignKey(Page)
container = models.ForeignKey(Container, blank=True, null=True)
content = models.ForeignKey(Content)
interaction_node = models.ForeignKey(InteractionNode)
kind = models.CharField(max_length=3, choices=INTERACTION_TYPES)
我希望能够进行一次查询以获取按容器分组的交互计数,然后按种类分组。输出 JSON 数据结构(由活塞负责序列化)的想法如下所示:
"data": {
"container 1": {
"tag_count": 3,
"com_count": 1
},
"container 2": {
"tag_count": 7,
"com_count": 12
},
...
}
SQL 将如下所示:
SELECT container_id, kind, count(*) FROM rb_interaction GROUP BY container_id, kind;
关于如何使用 ORM 按多个字段分组的任何想法? (如果可以避免 id,我不想为这个项目编写原始查询)这似乎是一个简单而常见的查询。
在你问之前:我已经看过 django 聚合文档和原始查询文档。
更新 根据以下建议,我创建了一个自定义管理器来处理此问题:
class ContainerManager(models.Manager):
def get_query_set(self, *args, **kwargs):
qs = super(ContainerManager, self).get_query_set(*args, **kwargs)
qs.filter(Q(interaction__kind='tag') | Q(interaction__kind='com')).distinct()
annotations = {
'tag_count':models.Count('interaction__kind'),
'com_count':models.Count('interaction__kind')
}
return qs.annotate(**annotations)
这仅计算类型标签或 com 的交互,而不是通过 group by 检索标签和 com 的计数。很明显,它从代码中以这种方式工作,但想知道如何修复它......
【问题讨论】:
标签: django django-models django-orm django-piston