You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wagtail:通过外键访问索引页时如何筛选其子页面

解决Wagtail中OrganizationPage展示对应组织最新新闻的问题

核心思路

由于NewsArticlePage已通过外键关联到Organization,直接从组织的关联新闻中筛选最新3条即可,无需绕NewsIndexPage的children方法,逻辑更高效清晰。

修改步骤

1. 在OrganizationPage中添加获取最新新闻的方法

修改organizations/models.py中的OrganizationPage类,新增方法获取当前组织的最新3条已发布新闻:

from news.models import NewsArticlePage

class OrganizationPage(Page):
    # 现有代码保持不变...

    def get_latest_news(self):
        # 关联组织存在时,返回其最新3条已发布新闻
        if self.organization:
            return NewsArticlePage.objects.live().filter(
                organization=self.organization
            ).order_by("-date_published")[:3]
        return []

2. 更新模板代码

修改templates/organizations/organizations/organization_page.html,替换原新闻循环逻辑,并修正"查看更多"链接的slug来源:

<!-- ... -->
<div class="container">
    <div class="row">
        <div class="news-articles-list">
            {% if page.news_section %}
                <h2 class="featured-cards__title">{{ page.news_section_title }}</h2>
                <div class="row">
                    {% for news_article in page.get_latest_news %}
                        {% include "includes/card/news-listing-card.html" with news_article=news_article %}
                    {% empty %}
                        <p>No news articles available.</p>
                    {% endfor %}
                </div>
                {% if page.organization %}
                    <a class="featured-cards__link" href="/news/organization/{{ page.organization.slug }}">
                        <span>View more of our news</span>
                    </a>
                {% endif %}
            {% endif %}
        </div>
    </div>
</div>
<!-- ... -->

可选方案:通过关联的NewsIndexPage筛选

如果坚持要通过news_section关联的NewsIndexPage筛选新闻,可替换为以下方法:

class OrganizationPage(Page):
    # 现有代码保持不变...

    def get_organization_news_from_index(self):
        if self.organization and self.news_section:
            return NewsArticlePage.objects.live().filter(
                parent=self.news_section,
                organization=self.organization
            ).order_by("-date_published")[:3]
        return []

模板中对应替换为:

{% for news_article in page.get_organization_news_from_index %}

关键注意事项

  • 确保OrganizationPage的organization字段已正确关联到Organization实例,否则无法筛选对应新闻。
  • "查看更多"链接需使用page.organization.slug,而非page.slug,避免页面slug与组织slug不一致导致的错误跳转。
  • 使用live()方法确保只展示已发布的新闻,符合Wagtail页面状态逻辑。

内容的提问来源于stack exchange,提问作者user23517209

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:15:55