【问题标题】:Filtering out private pages from tags从标签中过滤掉私人页面
【发布时间】:2019-05-23 03:29:06
【问题描述】:

我最近在我的 Wagtail 网站中创建了一个标签云,但我遇到了一个问题,即出现一些标签(在我的网站中称为“主题”),其中只有私人文章/页面。

到目前为止,我做了这样的事情来获取每个标签中的文章数量,如果没有,则将它们过滤掉:

topics_with_articles = Topic.objects.annotate(num_articles=models.Count("articlepage")).filter(num_articles__gt=0)
filtered_topics = topics_with_articles.order_by("-num_articles").values("name", "slug", "num_articles")

我的模型是这样设置的:

from modelcluster.models import ParentalManyToManyField, ParentalKey
from modelcluster.tags import ClusterTaggableManager
from taggit.models import Tag, TaggedItemBase

@register_snippet
class Topic(Tag):
    class Meta:
        ordering = ["slug"]
        proxy = True
        verbose_name = "Topic"
        verbose_name_plural = "Topics"

class ArticleTopic(TaggedItemBase):
    content_object = ParentalKey("ArticlePage", related_name="article_topics")

class ArticlePage(Page):
    topics = ClusterTaggableManager(through="articles.ArticleTopic", blank=True)

我找不到一个简单的解决方案来让它工作,那么我该怎么做呢?

【问题讨论】:

    标签: django wagtail django-taggit


    【解决方案1】:

    Wagtail Slack chat 中的某个人在 taggit 未记录的 most_common 函数上建议了 this answer,所以我应用了这样的解决方案:

    articles = ArticlePage.objects.live().public().order_by("-date")
    topics_with_filtered_articles = ArticlePage.topics.most_common(min_count=1, extra_filters={'articlepage__in': articles})
    

    这会通过比较 articlesArticles.objects 查询集从主题中过滤掉所有私人和草稿文章。通过添加min_count=1 参数,所有没有文章的主题也会被过滤掉。

    另外,taggit 在topics_with_filtered_articles 查询集中做了一个num_times 注释,所以我不必自己做!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 2016-05-10
      • 1970-01-01
      • 2016-12-24
      • 2015-06-26
      • 2022-01-05
      相关资源
      最近更新 更多