python - django 使用 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
。
解决方案
您可以尝试在计数之前使用条件表达式:
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'))
推荐阅读
- django - 这是构建模型的好方法吗?
- html - cPanel 不允许我将 Cron 作业设置为每分钟运行一次
- html - 如何在 HTML/CSS 中选择多个重叠相邻图像的出现顺序?
- c# - 我可以在 C# 中链接多个“或”(||) 运算符吗?
- javascript - 如何在 javascript 中正确使用 DOM 样式的边距顶部属性?
- powerbi - 有没有办法在powerbi的报告页面上轻松计算表格中的行数?
- html - Angular 材料目录的 HTML 代码
- javascript - 如何将特定索引的数组分配给另一个嵌套数组?
- python - 导入 firestore 时没有名为“google.api_core.client_options”的模块
- python-3.x - 带有 statsmodels 的 sm.OLS.from_formula('variable1 ~ variable2 + x ') 问题