H00man
H00man

Reputation: 387

change raw query into django models

i want to use django models feature to excute this sql query.

SELECT COUNT(DISTINCT ques_id), title FROM contest_assignment WHERE grp_id = 60 GROUP BY title;

i tried this but it did not give me proper result:

from django.db.models import Count assignment.objects.values_list('title').annotate(count=Count('ques')).values('title', 'count')

how can i use django model?

Upvotes: 1

Views: 187

Answers (1)

knbk
knbk

Reputation: 53649

You shouldn't use both .values() and .values_list(). The count field is implicitly added to the set of fields that is returned.

Django supports a COUNT(DISTINCT <field>) query by using .annotate(count=Count('<field>', distinct=True)). That would leave you with the following query:

(assignment.objects.filter(grp_id=60).values('title')
           .annotate(count=Count('ques_id', distinct=True)))

Upvotes: 1

Related Questions