Django中如何对get_object_or_404获取的分类下文章按最新日期排序
错误原因
written_on是Post模型的日期字段,你之前对Category查询集调用order_by的操作完全不相关,自然不会生效。你需要排序的目标是当前分类关联的所有Post文章,而非分类本身。
正确实现代码
修改你的视图函数,拿到分类后主动查询关联的文章并按日期倒序,再传入上下文即可:
def single_category(request, slug): category = get_object_or_404(Category, slug=slug) categories = Category.objects.all() # 按撰写日期倒序查询当前分类下的所有文章 sorted_posts = category.post.all().order_by('-written_on') context = { 'category': category, 'categories': categories, 'posts': sorted_posts # 把排序后的文章传入模板 } return render(request, 'Blog/single-category.html', context)
之后在single-category.html模板中,直接循环posts变量展示文章即可:
{% for post in posts %} <!-- 你的文章展示代码 --> {% endfor %}
可选优化方案
如果你希望所有场景下查询Post时默认都按撰写日期倒序,可以直接在Post模型的Meta类中配置默认排序规则,后续无需每次调用order_by:
class Post(models.Model): # 你原有的字段定义保持不变 name = models.CharField(max_length=120) # ... 其余字段省略 class Meta: ordering = ['-written_on'] # 新增这行配置默认排序规则
配置后直接调用category.post.all()拿到的就是已经按日期倒序排好的文章列表。
内容的提问来源于stack exchange,提问作者kendall-johnston
相关产品推荐
相关产品推荐

