Specify a group by field in django 1.2

I want to use annotateto count the number of events in my model, however, it does not use the correct field in the status group. instead of using the field that I want (i.e. specified in the count function), it uses the primary key of the model. eg.

ObjectHistory.objects.annotate(revisions=Count('resource'))

creates sql

SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`history_id`

where history_idis the primary key of ObjectHistory

I want to:

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'))

he placed the desired group by field, but then I did not have access to other fields in the model.

How to specify to use resource_id in a group by field?

+3
source share
2 answers

use the original method as described here

eg.

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

0

Try:

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

Source: https://habr.com/ru/post/1748846/


All Articles