Django MPTT queryset for instances with children with a certain attribute
<p>I'm using <a href="https://pypi.python.org/pypi/django-mptt/" rel="nofollow noreferrer">Django MPTT</a>, with the model Foobar like this:</p>

<pre><code>class Foobar(MPTTModel):
     parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
</code></pre>

<p>If I want to select all Foobars with children, I can do this:</p>

<pre><code>[x for x in Foobar.objects.all() if x.get_children().exists()]
</code></pre>

<p>If I want to select all Foobars that have children with a certain attribute (like <code>published</code>), I can do this:</p>

<pre><code>[x for x in Foobar.objects.all() if x.get_children().filter(published=True).exists()]
</code></pre>

<p>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 <a href="https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to" rel="nofollow noreferrer"><code>limit_choices_to</code></a> argument of <code>ForeignKey</code>:</p>

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