Use Specific() Method On PageQuerySet To Access Referenced Model's Field Data in Wagtail CMS

Jan 20, 2017 ยท Updated: Jul 12, 2021 ยท by Tim Kamanin

Wagtail CMS provides a very handy content tree that really helps in organizing website's content hierarchy. The tree itself is powered by django-treebeard library (https://github.com/django-treebeard/django-treebeard.

As a developer you should be aware of several handy methods that you can execute on any item of a tree (page):

page.get_children()  # returns a list of the current page children
page.get_parent()  # returns a list of the current page parents
page.get_next_sibling()  # returns a next sibling of the current page
page.get_prev_sibling()  # returns a previous sibling of the current page

The problem with these methods is that it returns all pages as instances of the base wagtail.wagtailcore.models.Page class, which isn't always what we want. Especially, when we need to access data stored in our retrieved page fields (besides title field, which is always available).

There's a cure for that: use a specific() method on any queryset result, like this:


It'll return results as their most specific type (class) and you can now access page fields without any issues.

The same trick can be used in Django templates too, here's an example:

{% for child in page.get_children.specific %} {{ child.body }} // We render a
body field contents here as an example. {% endfor %}

Hope this helps, enjoy Wagtailing ๐Ÿง !

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email โ†“ โ†“ โ†“