LearnWagtail.com has a new look! A new course is coming, too! 🥳

Tutorial Wagtail Version: 2.x

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

When querying for a Wagtail Page that has child (Subclassed) pages, you'll receive all of the pages in your QuerySet. There are times when you simply want the child pages (all types), a specific type of child page, or just the parent page itself with no children. In this lesson we'll explore Wagtails .not_exact_type() and .exact_type() methods.

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.

Related tutorials

Get notified about new Wagtail content.