django 1.2 中按字段指定分组
我想使用 annotate
来计算模型中出现的次数,但是它没有使用 group by 语句中的正确字段。它没有使用我想要的字段(即计数函数中指定的字段),而是使用模型的主键。例如,
ObjectHistory.objects.annotate(revisions=Count('resource'))
生成 sql
SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`history_id`
,其中 history_id
是 ObjectHistory 的主键,
我想要的是:
SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`resource_id
我发现通过将
ObjectHistory.objects.values.('resource').annotate(revisions=Count('resource'))
其放入正确的按字段分组,但随后我无法访问模型中的其他字段。
如何指定在分组依据字段中使用resource_id?
I want to use annotate
to count the number of occurances in my model, however it is not using the right field in the group by statment. instead of using the field i want (i.e. the one specified in the count function) it uses the primary key of the model. e.g.
ObjectHistory.objects.annotate(revisions=Count('resource'))
produces sql
SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`history_id`
where history_id
is the primary key of ObjectHistory
what I want is:
SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`resource_id
I found that by putting
ObjectHistory.objects.values.('resource').annotate(revisions=Count('resource'))
it put the right group by field but then i didn't have access to the other fields in the model.
How do I specify to use resource_id in the group by field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
Try:
使用此处记录的原始方法,
例如
use the raw method as documented here
e.g.