[英]Find Django model records that have more than one 'child' objects?
If I have two models in Django, Parent
and Child
, where Child
has a foreign key relationship to Parent
like this:如果我在 Django 中有两个模型,
Parent
和Child
,其中Child
与Parent
有外键关系,如下所示:
class Parent(models.Model):
parent_name = models.CharField(max_length=128, blank=False, default='no name')
class Child(models.Model):
child_name = models.CharField(max_length=128, blank=False, default='no name')
parent = models.ForeignKey('app.Parent', on_delete=models.CASCADE, null=False)
How can I find all Parent
records that have at least two Child
records?如何找到至少有两个
Child
记录的所有Parent
记录? Ideally, the solution would use a single .filter()
statement on Parent
.理想情况下,该解决方案将在
Parent
上使用单个.filter()
语句。
You can annotate on the number of Child
s and then filter on that number, like:您可以注释
Child
的数量,然后对该数字进行过滤,例如:
from django.db.models import Count
Parent.objects.annotate(
nchild=Count('child')
).filter(
nchild__gt=1)
This will generate a query like:这将生成如下查询:
SELECT parent.*, COUNT(child.id) AS nchild
FROM parent
LEFT OUTER JOIN child ON parent.id = child.parent_id
GROUP BY parent.id
HAVING COUNT(child.id) > 1
One can change the .filter(..)
condition to all sorts of conditions on the number of childs nchilds
, for example nchild=4
filters on Parent
s with exactly four children, whereas ~Q(nchild=7)
will exclude all Parent
s with exactly seven children.可以将
.filter(..)
条件更改为关于孩子数nchilds
各种条件,例如nchild=4
过滤器Parent
上正好有四个孩子,而~Q(nchild=7)
将排除所有Parent
s正好有七个孩子。 We can thus make more complicated filters.因此,我们可以制作更复杂的过滤器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.