首页 > 解决方案 > django 使用 Count() 一次注释相关字段

问题描述

我的Profile模型在一个模型中有两个 m2m 字段 -regioncountry. 如您所知,country有自己region的外键。

我想尝试计算每个区域的配置文件 - 不仅包括region而且在country__region.

即)如果有些人只有Africa地区,而其他人只有Congo国家(地区Africa),我想过滤它们。

我尝试使用annotate. 我可以像下面这样单独找到地区的数量

    profiles = Profile.objects.all()
    region_count = profiles.values('region').annotate(region_count=Count('region'))
    country_count = profiles.values('region').annotate(region_count=Count('country__region'))

但是我怎样才能计算具有特定区域的查询集,一次过滤regionregion__country?有什么可行的方法吗?

这是我的个人资料/国家/地区模型。区域模型只有名称字段。

class Profile(models.Model):
    region = models.ManyToManyField(
        Region,
        verbose_name="Region(s) of interest",
        blank=True,
    )
    country = models.ManyToManyField(
        Country,
        related_name="country",
        verbose_name="Countries of interest",
        blank=True,
    )
    ...

class Country(models.Model):
    region = models.ForeignKey(
        Region,
        null=True,
        blank=True,
    )
    ...

谢谢你的帮助。

概括

我想用regioncountry__region一次计算查询集annotate

标签: pythondjangoannotate

解决方案


您可以尝试在计数之前使用条件表达式:

from django.db.models import Case, When, F, Count

Profile.objects.annotate(
    reg=Case(
        When(region__isnull=True, then=F('country__region')),
        default=F('region'))
    ).values('reg').annotate(region_count=Count('reg'))

推荐阅读