Tutorial Summary

Wagtail Page's can have ForeignKeys to other pages. In this tutorial you'll learn how to return better ForeignKey data in your Headless Wagtail CMS website.

from rest_framework.fields import Field
from wagtail.core.models import Page


class BannerCTASerializer(Field):
    def to_representation(self, page):
        return {
            'id': page.id,
            'title': page.title,
            'first_published_at': page.first_published_at,
            'owner': page.owner.username,
            'slug': page.slug,
            'url': page.url,
        }


class HomePage(Page):
    # .. other fields 
    banner_cta = models.ForeignKey(
        "wagtailcore.Page",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )

    # Your api fields 
    api_fields = [
        APIField("banner_cta", serializer=BannerCTASerializer()),
    ]
Sign up for our newsletter

Get notified about new lessons :)


Our Sites