Django中如何展示含已发布文章的分类列表
解决Django分类下仅展示已发布文章的问题
这里有三种可行的解决方式,按需选择:
方法一:模板层直接过滤
直接在模板循环中添加条件判断,只渲染状态为published的文章:
修改后的模板代码:
{% for cat in categories %} <h2 class="catTitle"> {{cat.Title}} </h2> <ol class="itemTitle"> {% for post in cat.information_posts.all %} {% if post.status == 'published' %} <li><a href="{{post.geturl}}">{{post.Title}}</a></li> {% endif %} {% endfor %} </ol> {% endfor %}
方法二:视图层优化(推荐)
在视图中使用prefetch_related预取过滤后的已发布文章,避免多次数据库查询(N+1问题),性能更优:
修改后的视图代码:
from django.db.models import Prefetch def getInformed(request): template = 'getinformed/information-cat-list.html' categories = InformationCategory.objects.filter(Available=True).prefetch_related( Prefetch( 'information_posts', queryset=InformationPost.objects.filter(status='published'), to_attr='published_posts' ) ) args = { 'categories': categories, } return render(request, template, args)
对应模板需改成循环published_posts:
{% for cat in categories %} <h2 class="catTitle"> {{cat.Title}} </h2> <ol class="itemTitle"> {% for post in cat.published_posts %} <li><a href="{{post.geturl}}">{{post.Title}}</a></li> {% endfor %} </ol> {% endfor %}
方法三:自定义模型Manager(持久化过滤规则)
在InformationPost模型中定义自定义Manager,让关联查询默认只返回已发布文章:
修改后的模型代码:
from django.db import models class PublishedPostManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class InformationCategory(models.Model): # 字段定义 class InformationPost(models.Model): informations = models.ForeignKey(InformationCategory, on_delete=models.CASCADE, related_name="information_posts" ) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') # 自定义Manager objects = models.Manager() # 保留默认Manager,用于查询所有文章 published = PublishedPostManager() # 仅查询已发布文章的Manager
模板中可直接调用自定义Manager:
{% for cat in categories %} <h2 class="catTitle"> {{cat.Title}} </h2> <ol class="itemTitle"> {% for post in cat.information_posts.published.all %} <li><a href="{{post.geturl}}">{{post.Title}}</a></li> {% endfor %} </ol> {% endfor %}
内容的提问来源于stack exchange,提问作者Saidmamad
相关产品推荐
相关产品推荐

