简体   繁体   English

查找具有多个“子”对象的 Django 模型记录?

[英]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 中有两个模型, ParentChild ,其中ChildParent有外键关系,如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM