Skip to main content
 首页 » 编程设计

python之过滤 Django 新闻帖子

2024年08月30日28zdz8207

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

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

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

显示最新 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> 

谢谢,

乔希

请您参考如下方法:

只需将 .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() 相同格式的参数,只是相反!