繁体   English   中英

Django MPTT查询集,用于具有具有特定属性的子代的实例

[英]Django MPTT queryset for instances with children with a certain attribute

我正在使用Django MPTT和Foobar模型,如下所示:

class Foobar(MPTTModel):
     parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

如果要选择所有带孩子的Foobars,可以执行以下操作:

[x for x in Foobar.objects.all() if x.get_children().exists()]

如果我要选择所有具有特定属性的子代的Foobars(例如published ),则可以执行以下操作:

[x for x in Foobar.objects.all() if x.get_children().filter(published=True).exists()]

但是,我无法找到一种在一个查询中执行此操作的方法。 我需要在一个查询中执行此操作才能将其用于ForeignKeylimit_choices_to参数:

class Example(models.Model):
    related_foobar = models.ForeignKey(
        Foobar,
        limit_choices_to=Q(....), # How do I make this work?
    )

好吧,通过__isnull过滤器过滤了成为父母的纯净属性。 这通常适用于反向外键测试:

Foobar.objects.filter(children__isnull=False)  # must have children

应该指出的是, 'children'在此查询是related_query_name中的ForeignKey 如果提供此名称,则默认为related_name或小写的模型名称(在这种情况下为foobar )。

有了具体的子属性,您可以执行以下操作:

Foobar.objects.filter(children__published=True)

这将仅包括Foobars了至少一个孩子的Foobars

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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