Django: Group by one field

309 views Asked by At

I have a Django filter where I count sf_contactid as deals.

RelationshipContact.objects.values('sf_contactid')\
    .annotate(deals=Count('sf_contactid'))\
    .values('sf_contactid', 'pk', 'full_name', 'deals')\
    .order_by('-deals')[:250]

As result I have the following SQL query:

SELECT
    `web_relationshipcontact`.`sf_contactid`,
    `web_relationshipcontact`.`id`,
    `web_relationshipcontact`.`full_name`,
    COUNT(`web_relationshipcontact`.`sf_contactid`) AS `deals`
FROM `web_relationshipcontact`
GROUP BY
    `web_relationshipcontact`.`sf_contactid`,
    `web_relationshipcontact`.`id`,
    `web_relationshipcontact`.`full_name`
ORDER BY `deals` DESC LIMIT 250

But I want to group only by sf_contactid. How to change Django filter to make query simillar to bellow without using RAW SQL:

SELECT
    `web_relationshipcontact`.`sf_contactid`,
    `web_relationshipcontact`.`id`,
    `web_relationshipcontact`.`full_name`,
    COUNT(`web_relationshipcontact`.`sf_contactid`) AS `deals`
FROM `web_relationshipcontact`
GROUP BY
    `web_relationshipcontact`.`sf_contactid`
ORDER BY `deals` DESC LIMIT 250
1

There are 1 answers

0
gizmondo On

The latter query is illegal in many databases (e.g. postgres), so I doubt you can do that in django.