henriquebastos / django-aggregate-if

Conditional aggregates for Django queries, just like the famous SumIf and CountIf in Excel.
MIT License
138 stars 17 forks source link

Count ForeignKey problem #16

Open alexsilva opened 9 years ago

alexsilva commented 9 years ago

Django 1.4

qs.query.group_by = ['candidate_id', 'campaign_id']
qs = QuerySet(query=qs.query, model=self.model)  # for group by work

qs = qs.annotate(
 vote_approved=Count('candidate', only=Q(approved=True)),
 vote_analyse=Count('candidate', only=Q(approved__isnull=True)),
 vote_reproved=Count('candidate', only=Q(approved=False)),
 ultimo_voto=Max('created')
)

Sql

SELECT 
`app_bestemployee`.`id`, 
`app_bestemployee`.`voter_id`, 
`app_bestemployee`.`candidate_id`, 
`app_bestemployee`.`campaign_id`, 
`app_bestemployee`.`justification`, 
`app_bestemployee`.`justification_cancel`, 
`app_bestemployee`.`approved`, 
`app_bestemployee`.`created`, 
`app_bestemployee`.`updated`, 

MAX(`app_bestemployee`.`created`) AS `ultimo_voto`, 
COUNT(CASE WHEN `app_bestemployee`.`approved` IS NULL THEN `app_bestemployee`.`candidate_id` ELSE null END) AS `vote_analyse`, 
COUNT(CASE WHEN `app_bestemployee`.`approved` = '0'  THEN `app_bestemployee`.`candidate_id` ELSE null END) AS `vote_reproved`, 
COUNT(CASE WHEN `app_bestemployee`.`approved` = '1'  THEN `app_bestemployee`.`candidate_id` ELSE null END) AS `vote_approved` 

FROM `app_bestemployee` GROUP BY (candidate_id), (campaign_id) ORDER BY NULL

The ForeignKey count works but to seek reference in queryset have an invalid object.

qs[0].candidade -- is null

I do not know if 'aggregate-if' works in my case, but it almost solves my problems. I would like to keep references to 'candidate' and yet count based on approved.

henriquebastos commented 9 years ago

What version of django and python are you using?

Can you provide a PR with the failing tests?

alexsilva commented 9 years ago

Python 2.7 Django 1.4

Backend Mysql

The project is immense and is private, unfortunately I can not provide it.

But I passed the main part of the implementation above.