我正在尝试显示相关帖子,相关性基于类别。Post 模型具有类别模型的外键。
有没有更好的方法来做到这一点。目前我正在使用会话从 single_post_detail_view 发送 category_name 到自定义 context_processor 函数,然后返回与该类别相关的帖子。
视图.py
class PostDetailView(DetailView):
def get(self, request, slug):
post = Post.objects.get(slug=self.kwargs['slug'])
context = {
'post' : post
}
request.session['category'] = post.category.name
return render(request, 'blog/post_detail.html', context)
context_processors.py
from blog.models import Category
def related_posts(request):
if request.session['category']:
category = request.session['category']
return {
'related_posts': Category.objects.get(name=category).posts.all()
}
然后在 HTML
{% for post in related_posts %}
<a href="post.get_absolute_url()">{{post.title}}</a>
{% endfor %}