Django:按一个字段分组

时间:2013-12-29 16:19:09

标签: python sql django django-filters

我有一个Django过滤器,我将sf_contactid视为交易。

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

结果我有以下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`,
    `web_relationshipcontact`.`id`,
    `web_relationshipcontact`.`full_name`
ORDER BY `deals` DESC LIMIT 250

但我想只通过sf_contactid进行分组。 如何在不使用RAW SQL的情况下更改Django过滤器以使查询simillar低于标准:

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 个答案:

答案 0 :(得分:0)

后一种查询在许多数据库(例如postgres)中都是非法的,所以我怀疑你能在django中做到这一点。