wagtail api 如何公开片段和序列化嵌套数据

wagtail api how to expose snippets and serialize nested data

问题是这样的,我已经创建了一个片段,我想公开它,但我不知道如何序列化嵌套数据。这是我的代码:

models.py

@register_snippet
class TeamMember(ClusterableModel):
    name = models.CharField(max_length=80)
    description = models.CharField(max_length=80)

    panels = [
        FieldPanel('name'),
        InlinePanel('tasks', label=('Tasks')),
    ]

class Task(Orderable):
    team_member = ParentalKey('adm.TeamMember', related_name="tasks")
    task_name = models.CharField(max_length=80)

endpoints.py

class TeamMemberAPIEndpoint(BaseAPIViewSet):

    model = TeamMember

    body_fields = BaseAPIViewSet.body_fields + [
        'name',
        'description',
        'tasks',
    ]

    listing_default_fields = BaseAPIViewSet.listing_default_fields = [
        'name',
        'description',
        'tasks',
    ]

结果是:

    "items": [
        {
            "name": "python team",
            "description": "",
            "tasks": [
                {
                    "id": 1,
                    "meta": {
                        "type": "adm.Task"
                    }
                },
                {
                    "id": 2,
                    "meta": {
                        "type": "adm.Task"
                    }
                }
            ]
        }

我该如何解决这个问题?

您有多种获取嵌套数据的方法。

  1. 为 API 端点内的嵌套项提供专用序列化程序。

  2. 鹡鸰之道。定义额外的 api 属性。


from rest_framework import serializers
from wagtail.api import APIField


class Task(Orderable):
    team_member = ParentalKey('adm.TeamMember', related_name="tasks")
    task_name = models.CharField(max_length=80)

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = (
            "id",
            "task_name",
        )

@register_snippet
class TeamMember(ClusterableModel):
    name = models.CharField(max_length=80)
    description = models.CharField(max_length=80)

    panels = [
        FieldPanel('name'),
        InlinePanel('tasks', label=('Tasks')),
    ]

   api_fields = [
        APIField("tasks", serializer=TaskSerializer(many=True)),
    ]

响应如下所示:

{
    "meta": {
        "total_count": 1
    },
    "items": [
        {
            "name": "Member 1",
            "tasks": [
                {
                    "id": 1,
                    "task_name": "Do this"
                },
                {
                    "id": 2,
                    "task_name": "Do that"
                }
            ]
        }
    ]
}