gpt4 book ai didi

python - django 使用 Count() 一次性注释相关字段

转载 作者:行者123 更新时间:2023-12-01 09:15:43 25 4
gpt4 key购买 nike

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

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

即)如果一些国家只有非洲地区,而其他国家只有刚果国家(地区为非洲),我想将它们过滤为一个。

我尝试使用注释来解决它。我可以单独找到区域的数量,如下所示

    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,
)
...

感谢您的帮助。

摘要

我想使用annotate同时对regioncountry__region的查询集进行计数。

最佳答案

您可以尝试使用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'))

关于python - django 使用 Count() 一次性注释相关字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51281208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com