嵌套关系 wagtail api

Nested relationships wagtail api

我有以下数据结构:

{"related_cases": [
    {
        "type": "related_case_block",
        "value": {
            "case": 13,
            "short_text": "Case 2 is related!"
        },
        "id": "3aec5efe-55dc-441f-aa5c-fbbb801d237a"
    }
]}

相关案例是一个内部有块的streamfield。每个块都包含对另一个案例页面的引用。在这种情况下是 13。

我想将此案例中的一些字段包含到响应中,如下所示:

 {"related_cases": [
    {
        "type": "related_case_block",
        "value": {
            "case": {
                "id": 13,
                "title": "Case 2"
            },
            "short_text": "Case 2 is related!"
        },
        "id": "3aec5efe-55dc-441f-aa5c-fbbb801d237a"
    }
]}

任何人都可以解释一下我将如何完成这个吗?

假设您已将 related_case_block 定义为 StructBlock 的子 class,您可以覆盖 class 上的 get_api_representation 方法:

class RelatedCaseBlock(blocks.StructBlock):
    # ...
    def get_api_representation(self, value, context=None):
        return {
            'case': {
                'id': value['case'].id
                'title': value['case'].title
            },
            'short_text': value['short_text']
        }