Wagtail: Filter Page model by a field on the child

786 views Asked by At

I have two models, ParentPage and ChildPage. I want to find the set of ParentPages where a field is_completed is True on the ChildPage.

Normally in Django, I could do something like

ParentPage.objects.filter(child_page__is_completed=True)

However, I don't think there is a join here for the Wagtail/Treebeard hierarchy.

I also thought you might be able to filter ChildPages by multiple ParentPages, e.g. ChildPage.objects.children_of([parent_ids]), but I can't see a way to do that either.

Is there a simpler way?

1

There are 1 answers

1
allcaps On BEST ANSWER

The Page table has path and url_path columns. If you find all children and strip the last part of the path or url_path, you can use that result to query the parent pages.

Path:

child_paths = ChildPage.objects.filter(is_completed=True).values_list("path", flat=True)
parent_paths = set([cp[:-4] for cp in child_paths])
pages = Page.objects.filter(path__in=parent_paths)

Url path:

child_urls = ChildPage.objects.filter(is_completed=True).values_list("url_path", flat=True)
parent_urls = set([url.rsplit('/', 1)[0] for url in child_urls])
pages = Page.objects.filter(url_path__in=parent_urls)

Disclaimer: untested code.