您根本不需要创建自定义 API 端点。相反,您会告诉 Django Rest Framework 在尝试序列化您的模型字段时要返回什么。
下面是一个如何使用带有 ClusterTaggableManager (tags) 的自定义序列化程序的示例
from modelcluster.contrib.taggit import ClusterTaggableManager
from rest_framework.fields import Field
from wagtail.core.models import Page
from wagtail.api import APIField
class CustomTagSerializer(Field):
"""Custom Tag Serializer."""
def to_representation(self, value):
"""Loop through all the tags and return the name, slug and caption as a Dict."""
return [
{
"name": tag.name,
"slug": tag.slug,
"pk": tag.pk
}
for tag in value.all()
]
class BlogPage(Page):
"""Custom Wagtail Page with Tags."""
# ... other fields
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
api_fields = [
APIField("title"),
# ... other fields to turn into JSON
APIField("tags", serializer=CustomTagSerializer()),
]
您将使用 api_fields = [APIField(), APIField()...] 和一个采用 Field 类的 serializer。在to_representation() 方法中,您可以遍历所有标签并返回一个字典列表(我在上面的示例中编写了一个列表理解)。
如果您打开 localhost:8000/api/v2/pages/{page_id},您会看到与此非常相似的 JSON:
{
"id": 4,
"meta": {
"...": "...",
},
"title": "Blog Page",
"tags": [
{
"name": "Multiple worded tag",
"slug": "multiple-worded-tag",
"pk": 1
},
{
"name": "tag1",
"slug": "tag1",
"pk": 2
}
]
}