Django/Wagtail/taggit - 获取模型特定标签列表

Django/Wagtail/taggit - Getting model specific tag list

我看过这个:

那里的解决方案生成了所有存储标签的列表,即图像、文档等标签。

我正在努力实现类似的目标。在新闻索引页面上,有一个新闻页面标签的下拉列表。

我似乎无法获得只有新闻页面标签的标签列表,目前这为我提供了我网站中所有标签的列表,包括图像和文档标签。

from django.template.response import TemplateResponse
from modelcluster.fields import ParentalKey, ParentalManyToManyField
from modelcluster.tags import ClusterTaggableManager
from taggit.models import TaggedItemBase, Tag
from core.models import Page

class NewsPageTag(TaggedItemBase):
    content_object = ParentalKey('NewsPage', related_name='tagged_items')


class NewsPage(Page):
    tags = ClusterTaggableManager(through=NewsPageTag, blank=True)


class NewsIndexPage(Page):

    def serve(self, request, *args, **kwargs):
        context['tags'] = Tag.objects.all().distinct('taggit_taggeditem_items__tag')
        return TemplateResponse(
            request,
            self.get_template(request, *args, **kwargs),
            context
        )

我也试过:

from django.contrib.contenttypes.models import ContentType
# ...
def serve(self, request, *args, **kwargs):
    news_content_type = ContentType.objects.get_for_model(NewsPage)
    context['tags'] = Tag.objects.filter(
        taggit_taggeditem_items__content_type=news_content_type
    )
    return TemplateResponse(
        request,
        self.get_template(request, *args, **kwargs),
        context
    )

它分配 context['tags'] 一个空集

我的模板:

{% if tags.all.count %}
    {% for tag in tags.all %}
        <a class="dropdown-item" href="?tag={{ tag.id }}">{{ tag }}</a>
    {% endfor %}
{% endif %}

求助!这个感觉不应该这么复杂。谢谢

您可以在新的 Wagtail Bakery Demo application 中复制这是如何实现的,这是一个很好的参考。

本质上只是获取所有子页面,然后获取它们的标签,使用set确保它们是唯一对象。

首先向您的 NewsIndexPage 添加一个方法,这将帮助您以一致的方式获取这些标签。

See: models.py

class NewsIndexPage(Page):

    # Returns the list of Tags for all child posts of this BlogPage.
    def get_child_tags(self):
        tags = []
        news_pages = NewsPage.objects.live().descendant_of(self);
        for page in news_pages:
            # Not tags.append() because we don't want a list of lists
            tags += page.get_tags
        tags = sorted(set(tags))
        return tags

因为你的 NewsPageIndex 模型有一个方法,你不需要覆盖 serve 方法,你可以像这样直接在你的模板中获取标签。

    {% if page.get_child_tags %}
        {% for tag in page.get_child_tags %}
            <a class="dropdown-item" href="?tag={{ tag.id }}">{{ tag }}</a>
        {% endfor %}
    {% endif %}

在 Wagtail Bakery Demo 的 blog_index_page.html

中查看类似的模板方法

注意:您仍然可以通过在 serve 方法中执行类似的操作来添加到上下文中:

context['tags'] = self.get_child_tags()