我是 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"}} »</a></span>
</div>
{% endfor %}
<span><a style="text-decoration: none; href="/news-hub/news/">View all news »</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()
格式相同的参数,它只是做相反的事情!
关于python - 过滤 django 新闻帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094530/