我的Profile
模型在一个模型中有两个m2m字段-region
和country
。如您所知,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'))
但是如何计算具有特定区域的查询集,同时使用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
的查询集。
答案 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'))