如何使用Django中的外键关系中的任何/ exists / all逻辑检索查询集?

问题描述 投票:1回答:2

假设我有两个模型:

from django.db import models

class Parent(models.Model):
    pass

class Child(models.Model):
    parent = models.ForeignKey(Parent,
                               on_delete=models.CASCADE,
                               related_name='children')
    active = models.BooleanField()

我如何获得至少有一个活跃孩子的父母查询集?换句话说,我如何获得排除那些没有活跃孩子的父母的查询集?如果在过滤器中使用模型属性是可行的,这将是一项微不足道的任务,但这是不可能的。这也是使用列表推导的简单操作,但重要的是查询集是最终结果。

python django model foreign-keys filtering
2个回答
1
投票

一种解决方案是使用聚合:https://docs.djangoproject.com/en/2.1/topics/db/aggregation/

我们可以使用它们拥有的活动子项数来注释父项的查询集,然后针对该查询集进行过滤,以仅查找数字大于或等于0的父项:

from django.db.models import Count, Q

num_active_children = Count('children', filter=Q(children__active=True))
parents_with_any_active_children = (Parent.objects
    .annotate(num_active_children=num_active_children)
    .filter(num_active_children__gte=1)
)

0
投票

Parent.objects.filter(child__active =真)

希望这对你来说已经足够了。

© www.soinside.com 2019 - 2024. All rights reserved.