New Wagtail Course! 🥳 The Ultimate Wagtail Developers Course

Tutorial Wagtail Version: 2.x

Getting Child Page Properties From a Subclassed Page

In Wagtail, and just like in Django, you can subclass classes. In this lesson, we're subclassing a Wagtail Page into 2 child pages. But when we query for all the parent classes, we're also given the child classes in the QuerySet, and the data is somewhat inconsistent because child classes can have unique fields that differ from their parents and siblings.

When you subclass a page in Wagtail and then create a query for all the parent pages, you'll also receive all the child pages with it. Sometimes that's good, sometimes that's bad. In the scenarios where you need additional child page fields you can't simply loop through your QuerySet and get them all. Instead, you'll need to use .specific in your template, or .specific(defer=False) in your Python view.

Below is an example of a QuerySet that's looped in our template, and some model assumptions.

``` # models.py from django.db import models class YourParentPage(Page): """Your Parent Page. Subclasses inherit this.""" custom_title = models.CharField(max_length=100) class YourChildPage(YourParentPage): """Your Child Page. Inherits From YourParentPage.""" subtitle = models.CharField(max_length=100) ```
``` # In your terminal all_posts = YourParentPage.objects.all() all_posts <PageQuerySet [<YourParentPage: Parent Page>, <YourChildPage:Child Article>]> ```
``` {# In your template #} {% for post in all_posts %} {{ post.title }} {# This is a wagtailcore.Page property; comes with all Page's #} {% if post.specific.subtitle %} <p>{{ post.specific.subtitle }}</p> {% endif %} {% endfor %} ```

In the above template we're checking for .specific which basically means: Check if there's a child page and if that child page has a property/field called subtitle.

The Git Commit

If you'd like to see the entire git commit, you can check it out here: https://github.com/CodingForEverybody/learn-wagtail/commit/08fbcd67748cec18d9fd8a59fd3c775f6be07aae

Related tutorials

The Ultimate Wagtail Developers Course

This course covers everything from basic installation to advanced features like custom blocks and API integration, it's perfect for developers looking to enhance their skills with this powerful CMS.

Ultimate Wagtail Developers Course Logo