python - 过滤 django 新闻帖子

标签 python django

我是 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() 格式相同的参数,它只是做相反的事情!

关于python - 过滤 django 新闻帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094530/

相关文章:

python - 如何从该表构建所有可能元组的列表?

python - 在django admin中使用代理模型自定义更改 ListView

python - Django:icontains 大小写对 unicode 敏感

python - 为什么我的自定义 404 页面在 Django 中返回 '404 ok' 响应?

python - 让 DataFrame 变小会让它变快吗?

python - Django 2 : TemplateDoesNotExist even if files placed properly

python - 如何生成一个不以 0 开头且具有唯一数字的随机 4 位数字?

python - Django post_delete : count all objects which have one matching attribute with deleted object

Django 休息 : How do i return SimpleJWT access and refresh tokens as HttpOnly cookies with custom claims?

python - 在 Python 中查找最接近特定值的列表项