django使用Count()立即注释相关字段

时间:2018-07-11 08:54:27

标签: python django annotate

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

我想尝试计算每个区域的个人资料-不仅包括region,而且包括country__region

i.e。)如果某些区域仅具有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,
    )
    ...

感谢您的帮助。

摘要

我想用region一次计算country__regionannotate的查询集。

1 个答案:

答案 0 :(得分:1)

您可以在计数之前尝试使用conditional-expressions

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'))