开发者

specify group by field in django 1.2

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?


Try:

    ObjectHistory.objects.values.('resource').\
    extra(select_params=('attribute1', 'attribute2'))\
    .annotate(revisions=Count('resource'))


use the raw method as documented here

e.g.

ObjectHistory.objects.raw("SELECT *, COUNT(resources_objecthistory.resource_id) AS revisions FROM resources_objecthistory GROUP BY resources_objecthistory.`resource_id")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜