Add more fields to LMOTFY serializer

This commit is contained in:
Jake Howard 2022-08-25 00:27:31 +01:00
parent e6c44e9a8a
commit fb44600ca2
Signed by: jake
GPG key ID: 57AFB45680EDD477
2 changed files with 17 additions and 6 deletions

View file

@ -1,7 +1,7 @@
from rest_framework import serializers
from wagtail.models import Page
from website.blog.models import BlogPostListPage
from website.blog.models import BlogPostPage
class PageLinkSerializer(serializers.ModelSerializer):
@ -17,10 +17,19 @@ class PageLinkSerializer(serializers.ModelSerializer):
class LMOTFYSerializer(serializers.ModelSerializer):
full_url = serializers.SerializerMethodField()
image = serializers.SerializerMethodField()
class Meta:
model = BlogPostListPage
fields = read_only_fields = ["full_url", "title", "summary"]
model = BlogPostPage
fields = read_only_fields = ["full_url", "title", "summary", "image", "date"]
def get_full_url(self, page: Page) -> str:
def get_full_url(self, page: BlogPostPage) -> str:
return page.get_full_url(request=self.context["request"])
def get_image(self, page: BlogPostPage) -> str:
hero_image_url = page.hero_image_url
if isinstance(hero_image_url, str) and hero_image_url[0] == "/":
return self.context["request"].build_absolute_uri(hero_image_url)
return hero_image_url

View file

@ -6,7 +6,7 @@ from rest_framework.views import APIView
from wagtail.models import Page
from wagtail.query import PageQuerySet
from website.blog.models import BlogPostListPage
from website.blog.models import BlogPostPage
from . import filters, serializers
from .pagination import CustomPageNumberPagination
@ -45,4 +45,6 @@ class LMOTFYAPIView(ListAPIView):
pagination_class = CustomPageNumberPagination
def get_queryset(self) -> PageQuerySet:
return BlogPostListPage.objects.live().only("id", "url_path", "title", "body")
return BlogPostPage.objects.live().select_related(
"hero_image", "hero_unsplash_photo"
)