我有以下型号
class Domain(models.Model):
domain = models.URLField()
web_analytics = models.ManyToManyField('AnalyticsProvider', blank=True)
class AnalyticsProvider(models.Model):
name = models.CharField(max_length=50)
我想获得每个域的分析数量,然后他们按分析数量汇总它们。我想得到如下结果:{“1 分析提供者”:“520 域”,“2 分析提供者”:“130 域”,...}
. 我设法用 SQL 查询来做到这一点,但我想使用 django ORM,SQL 查询如下:
SELECT COUNT(1),"num_m2m" from (SELECT "dashboard_domain"."id_website", COUNT("dashboard_domain_web_analytics"."analyticsprovider_id") AS "num_m2m"
FROM "dashboard_domain" LEFT OUTER JOIN "dashboard_domain_web_analytics"
ON ("dashboard_domain"."id_website" = "dashboard_domain_web_analytics"."domain_id")
GROUP BY "dashboard_domain"."id_website") GROUP BY "num_m2m";
我尝试在查询集中进行双重注释,例如:
number_web_analytics = Domain.objects.annotate(num_m2m=Count('web_analytics')).annotate(count_domains=Count('num_m2m'))
但似乎 django 无法对另一个进行注释。