New Wagtail Course! 🥳 The Ultimate Wagtail Developers Course

Tutorial Wagtail Version: 2.x

Headless CMS: Serializing Foreign Keys

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()), ] ```

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