2

我是 Django 新手,我有一篇新闻文章,在同一个模板上,我在右侧有一个部分显示所有最新文章。但是,当您在主要新闻帖子之一上时,它也会显示在右侧的“最新新闻”选项卡中。

我很确定我需要使用 .exclude 过滤掉正在显示的那个。但是我不知道 django 如何知道正在显示哪个帖子。

如果您需要查看我的代码,请询问。我只使用基本模型/视图来输出数据。

显示最新 3 个帖子的行:

other_news = NewsPost.objects.filter(live=True, categories__in=post.categories.all).distinct().order_by("-posted")[:3]

模板代码:

<div class='related_article_wrapper'>
            {% if other_news %}
                {% for news in other_news %}

                <div class="article_snipppet_wrap">

                    <img class="article_icon" src="/media/images/article_icon.png"  alt="" />
                        <p>{{news.title}}</p>
                        <span><a href="{{news.get_absolute_url}}">{{news.posted|date:"d/m/y"}} &#187;</a></span>

                </div>


            {% endfor %}
            <span><a style="text-decoration: none; href="/news-hub/news/">View all news &#187;</a></span>
            {% endif %}

            </div>

谢谢,

乔什

4

1 回答 1

3

只需添加.exclude(id=post.id)到您的过滤器链:

other_news = NewsPost.objects.exclude(id=post.id).filter(live=True,    
    categories__in=post.categories.all).distinct().order_by("-posted")[:3]

exclude()采用与 相同格式的参数filter(),它只是做相反的事情!

于 2012-08-23T15:36:41.773 回答