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

Django DetailView如何限制上下篇文章仅展示已发布状态内容

解决方法

Django 自带的get_next_by_created_on方法不支持直接传入过滤条件,你可以在Post模型中自定义两个方法来实现筛选已发布状态的上下篇文章,具体操作如下:


1. 修改Post模型添加自定义方法

在你现有的Post模型代码中补充以下两个方法:

class Post(models.Model):
    # 你原有代码保持不变,新增下面两个方法
    def get_next_published(self):
        # 获取下一篇已发布的文章
        return Post.objects.filter(
            created_on__gt=self.created_on,
            status=1
        ).order_by('created_on').first()

    def get_previous_published(self):
        # 获取上一篇已发布的文章
        return Post.objects.filter(
            created_on__lt=self.created_on,
            status=1
        ).order_by('-created_on').first()

2. 修改模板调用自定义方法

替换原来的模板代码,调用我们新增的方法即可,这里用with标签缓存查询结果,避免重复请求数据库:

<ul class="text-center">
    {% with previous_post=post.get_previous_published %}
    {% if previous_post %}
    <li class="prev">
        <a rel="prev" href="{{ previous_post.get_absolute_url }}">
            {{ previous_post.title }}
        </a>
    </li>
    {% endif %}
    {% endwith %}

    {% with next_post=post.get_next_published %}
    {% if next_post %}
    <li class="next">
        <a rel="next" href="{{ next_post.get_absolute_url }}">
            {{ next_post.title }}
        </a>
    </li>
    {% endif %}
    {% endwith %}
</ul>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:27:05