[英]Django MPTT queryset for instances with children with a certain attribute
I'm using Django MPTT , with the model Foobar like this: 我正在使用Django MPTT和Foobar模型,如下所示:
class Foobar(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
If I want to select all Foobars with children, I can do this: 如果要选择所有带孩子的Foobars,可以执行以下操作:
[x for x in Foobar.objects.all() if x.get_children().exists()]
If I want to select all Foobars that have children with a certain attribute (like published
), I can do this: 如果我要选择所有具有特定属性的子代的Foobars(例如
published
),则可以执行以下操作:
[x for x in Foobar.objects.all() if x.get_children().filter(published=True).exists()]
I can't work out a way to do this in one query, though. 但是,我无法找到一种在一个查询中执行此操作的方法。 I need to do it in one query in order to be able to use it for the
limit_choices_to
argument of ForeignKey
: 我需要在一个查询中执行此操作才能将其用于
ForeignKey
的limit_choices_to
参数:
class Example(models.Model):
related_foobar = models.ForeignKey(
Foobar,
limit_choices_to=Q(....), # How do I make this work?
)
Well, the pure property of being a parent is filtered for via the __isnull
filter. 好吧,通过
__isnull
过滤器过滤了成为父母的纯净属性。 This generally holds for reverse foreign key testing: 这通常适用于反向外键测试:
Foobar.objects.filter(children__isnull=False) # must have children
It should be mentioned that 'children'
in this query is the related_query_name
of the ForeignKey
. 应该指出的是,
'children'
在此查询是related_query_name
中的ForeignKey
。 This defaults to the related_name
if that is provided or to the lowercase model name ( foobar
in this case). 如果提供此名称,则默认为
related_name
或小写的模型名称(在这种情况下为foobar
)。
With a concrete child property, you can simply do: 有了具体的子属性,您可以执行以下操作:
Foobar.objects.filter(children__published=True)
This will only include Foobars
with at least one child that is published. 这将仅包括
Foobars
了至少一个孩子的Foobars
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.