vbv/server/vbv_lernwelt/learnpath/serializer_helpers.py

41 lines
1.4 KiB
Python

import wagtail.api.v2.serializers as wagtail_serializers
from rest_framework.fields import SerializerMethodField
from vbv_lernwelt.learnpath.utils import get_wagtail_type
def get_it_serializer_class(model, field_names):
return wagtail_serializers.get_serializer_class(model, field_names=field_names, meta_fields=[], base=ItBaseSerializer)
class ItTypeField(wagtail_serializers.TypeField):
def to_representation(self, obj):
name = get_wagtail_type(obj)
return name
class ItBaseSerializer(wagtail_serializers.BaseSerializer):
type = ItTypeField(read_only=True)
children = SerializerMethodField()
meta_fields = []
def __init__(self, *args, **kwargs):
self.descendants = kwargs.pop('descendants', None)
super().__init__(*args, **kwargs)
def get_children(self, obj):
if self.descendants:
children = _get_children(self.descendants, obj)
return [c.specific.get_serializer_class()(c.specific, descendants=self.descendants).data for c in children]
else:
return [c.specific.get_serializer_class()(c.specific).data for c in obj.get_children().specific()]
def _get_descendants(pages, obj):
return [c for c in pages if c.path.startswith(obj.path) and c.depth >= obj.depth]
def _get_children(pages, obj):
return [c for c in pages if c.path.startswith(obj.path) and obj.depth + 1 == c.depth]