views:

47

answers:

1

Hi,

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?

A: 

Try:

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