I'm using Django MPTT, with the model Foobar like this:
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:
[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:
[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
:
class Example(models.Model):
related_foobar = models.ForeignKey(
Foobar,
limit_choices_to=Q(....), # How do I make this work?
)