如何使用PageChooserBlocks的ListBlocks对StreamField的APIField进行JSON序列化

问题描述 投票:0回答:1

嗨,伙计们,我的头在想解决这个问题。我无法使用blocks.PageChooserBlock从流场api获得响应。我需要反序列化JSON,但是没用了。

我收到此错误Object of type 'TimelineEvent' is not JSON serializable

这是页面

class Timeline(Page):
    content = StreamField([
        ('title', blocks.CharBlock(classname="full title")),
        ('time_period', TimePeriodBlock())
    ])
    content_panels = Page.content_panels + [
        StreamFieldPanel('content')
    ]
    api_fields = [
        APIField("title"),
        APIField("content")
    ]

我能够从TimePeriodBlock获取数据,看起来像这样

class TimePeriodBlock(blocks.StructBlock):
    def get_api_representation(self, value, context=None):
        dict_list = []
        for item in value:
            temp_dict = {
                'period_name': value.get("period_name"),
                'description': value.get("description"),
                'duration': value.get("duration"),
                'events': value.get('events')
            }
            print(value.get('events'))
            dict_list.append(temp_dict)
            return dict_list
    period_name = blocks.CharBlock()
    description = blocks.CharBlock()
    duration = blocks.CharBlock()
    events = blocks.ListBlock(EventBlock())

但是无法在EventBlock附近获得任何东西

class EventBlock(blocks.StructBlock):
    def get_api_representation(self, value, context=None):
        dict_list = []
        print('here')
        print(value)
        for item in value:
            temp_dict = {
                # 'event': item.get("event"),
                'short_desc': item.get("short_desc"),
            }
            dict_list.append(temp_dict)
            print(dict_list)
        return dict_list
    event = blocks.PageChooserBlock(page_type=TimelineEvent)
    short_desc = blocks.CharBlock(max_length=250)

事件看起来像这样 [StructValue([('event', <TimelineEvent: Dance 1700 fandango and jota >), ('short_desc', 'first event')]), StructValue([('event', <TimelineEvent: Dance 1700 contredanse>), ('short_desc', '2nd event')])]

[StructValue([('event', <TimelineEvent: Dance 1937 Trudl Dubsky>), ('short_desc', '3rd')])]

django python-3.x django-rest-framework wagtail wagtail-streamfield
1个回答
0
投票

value.get(...)只会为您提供子块的原始值,而不是API表示形式。为此,您需要在子块上调用get_api_representation

        temp_dict = {
            'period_name': value.get("period_name"),
            'description': value.get("description"),
            'duration': value.get("duration"),
            'events': self.child_blocks['events'].get_api_representation(value.get("events"))
        }
© www.soinside.com 2019 - 2024. All rights reserved.