Learn Wagtail Course

How to only get Parent and Child Class Pages and their Specific Fields

There are several ways to query your Wagtail Pages and return QuerySets containing only the page classes you want. Below is some example code.

Just Parent Pages

This example assumes that there are child (subclassed) pages that inherit form BlogDetailPage.

parent_pages = BlogDetailPage.objects.live().exact_type(BlogDetailPage)

Just Child Pages

This example assumes each child page is inheriting from BlogDetailPage. This will return a QuerySet of BlogDetailPage's, not the actual class you'd be expecting.

child_pages = BlogDetailPage.objects.live().not_exact_type(BlogDetailPage)

Just Specific Child Pages

If you're trying to query for all child pages that inherit from a parent page (ie. BlogDetailPage), you'll receive a QuerySet of BlogDetailPage's. To get the specific child pages, append .specific() to your query.

child_pages = BlogDetailPage.objects.live().not_exact_type(BlogDetailPage).specific()

Disable Property Deferring

Wagtail is built for speed and efficiency. It's easy to get away from that and write code that performs terribly. So by default the .specific() argument called defer is set to True (.specific(defer=True)). Grabbing specific fields from a model means adding another database hit, and if the QuerySet is large, this can become a problem. So it's good that specific property deferring is enabled by default.

But occasionally you want the specific properties of a class. To disabled property deferring simply append .specific(defer=False) to your ORM Query.

Full Wagtail QuerySet Reference

Wagtail comes with a lot of different QuerySet options. This lesson only went over 2 of them, but there are many more. Definitely take a couple minutes and read through their docs page.

The Git Commit

This lesson works purely in the Django Shell and doesn't have any code to committed to the repo. Above is where you can find example code.

Was this helpful to you?

Sharing is caring. Help the community by sharing this article.