[英]Django | Aggregate Values from Foreign Key
I have two databases, A
and B
. 我有两个数据库
A
和B
B
contains a ForeignKey
to A
. B
包含A
的ForeignKey
。
When I do B.objects.filter(a_id=3).values('bags').count()
, I get the number I want, Y
. 当我执行
B.objects.filter(a_id=3).values('bags').count()
,我得到了想要的数字Y
What is the set of commands I need in order to add this number, Y
, as an annotation into database A
? 为了将此数字
Y
作为注释添加到数据库A
,我需要什么命令集?
Ideally, this would be an annotate
type of command. 理想情况下,这将是带
annotate
的命令。
The models look like: 这些模型如下所示:
class A(models.Model):
name = models.CharField(max_length=150)
class B(models.Model):
name = models.CharField(max_length=150)
a_id = models.ForeignKey(A, on_delete=models.CASCADE)
bags = models.ManyToManyField(Bags)
class Bags(models.Model):
name = models.CharField(max_length=150)
Try to use b__bags
lookup in annotation: 尝试在批注中使用
b__bags
查找:
from django.db.models import Count
A.objects.annotate(bags_count=Count('b__bags'))
from django.db.models import Count
A.objects.annotate(Y=Count('b__bags'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.