【问题标题】:Wagtail getting all tags of a specific page type using apiWagtail 使用 api 获取特定页面类型的所有标签
【发布时间】:2019-06-05 07:35:02
【问题描述】:

我正在尝试找到一种方法来使用 wagtail api 获取特定页面类型的标签列表。

 class BlogPage(FreeFormPage):
        #...
        tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
 class WorkPage(FreeFormPage):
        #...
        tags = ClusterTaggableManager(through=WorkPageTag, blank=True)

在文档中,很明显有页面、文档和图像的端点。但是我找不到关于标签的信息。

  1. 我是否必须创建另一个特定的页面类型模型来收集所有标签并通过页面端点发送它们?
  2. 还是我必须为标签模型添加自定义端点?

【问题讨论】:

    标签: wagtail django-taggit wagtail-apiv2


    【解决方案1】:

    您根本不需要创建自定义 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
            }
        ]
    }
    

    【讨论】:

    • 我认为,我的帖子不能代表我遇到的问题。我需要一种方法来达到 django-taggit 的标签模型(wagtail 正在使用 Django taggit)并获取特定页面的所有标签(通过 api )。就像'给我博客页面的标签'......
    • 您想要一个特定的端点just 来获取标签吗?因为您很可能已经发送了对博客页面(或博客列表页面)的请求,所以您可以使用我为此编写的方法。您也可以使用 Wagtail v2 API 访问字段并按页面类型进行过滤。例如:/api/v2/pages/?type=blog.BlogPage&fields=tags。 docs.wagtail.io/en/v2.5.1/advanced_topics/api/v2/… 的文档中有更多相关信息
    猜你喜欢
    • 1970-01-01
    • 2011-11-13
    • 2015-12-16
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多