Skip to content
This repository has been archived by the owner on Nov 27, 2022. It is now read-only.

Count ForeignKey problem #16

Open
alexsilva opened this issue Jun 17, 2015 · 2 comments
Open

Count ForeignKey problem #16

alexsilva opened this issue Jun 17, 2015 · 2 comments

Comments

@alexsilva
Copy link

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
Copy link
Owner

henriquebastos commented Jun 17, 2015 via email

@alexsilva
Copy link
Author

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants