django 使用 Count() 一次注释相关字段
django annotate related fields at once with Count()
我的 Profile
模型在一个模型中有两个 m2m 字段 - region
和 country
。如您所知,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'))
但是我如何计算特定区域的查询集,同时使用 region
和 region__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__region
同时用 annotate
计算查询集。
你可以尝试在计数前使用 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'))
我的 Profile
模型在一个模型中有两个 m2m 字段 - region
和 country
。如您所知,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'))
但是我如何计算特定区域的查询集,同时使用 region
和 region__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__region
同时用 annotate
计算查询集。
你可以尝试在计数前使用 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'))