Wagtail:如何通过子页面字段筛选父页面模型?
Hey there! I’ve run into this exact scenario before with Wagtail’s page hierarchy. The key issue here is that Wagtail’s base Page model doesn’t know about your ChildPage-specific fields like is_completed—so we need to adjust our query to target the specific page type. Here are two solid approaches:
1. Using the children Relation with specific
Wagtail provides a specific relation that lets you access fields from your custom page subclasses. We’ll combine this with filtering to target only ChildPage instances where is_completed is True:
# Get all ParentPages with at least one completed ChildPage child parent_pages = ParentPage.objects.filter( children__model='your_app.childpage', # Replace with your app + model name children__specific__is_completed=True ).distinct()
- The
children__modelfilter ensures we’re only looking at child pages of typeChildPage(use the lowercaseapp_label.model_nameformat—you can get this fromChildPage._meta.label). distinct()is important because a single ParentPage might have multiple completed ChildPages, which would otherwise return duplicate ParentPage entries.
2. Using Subqueries (More Efficient)
For larger datasets, subqueries are often faster because they avoid joining tables and deduplicating results. We’ll use Django’s Exists and OuterRef to check if a ParentPage has any matching ChildPages:
from django.db.models import Exists, OuterRef parent_pages = ParentPage.objects.filter( Exists( ChildPage.objects.filter( parent=OuterRef('pk'), is_completed=True ) ) )
This query directly checks for the existence of at least one completed ChildPage under each ParentPage, which is both clean and performant.
Why Your Initial Attempts Didn’t Work
- The standard
ParentPage.objects.filter(child_page__is_completed=True)fails because there’s no directchild_pageforeign key relation—Wagtail uses a tree structure via Treebeard, so we need to use thechildrenrelation instead. ChildPage.objects.children_of([parent_ids])returns ChildPages, not ParentPages, so we need to reverse the query to start from ParentPage and check their children.
内容的提问来源于stack exchange,提问作者MDalt

