Как получить предыдущий и следующий связанный пост в django?
views.py
def post_details(request,pk):
post = Post.objects.get(id=pk)
# next_post = Post.objects.filter(id=pk)
context={'post':post,'next':next_post}
return render(request, 'blog/post_detail.html', context)
blog-detail
<div class="s-content__pagenav group">
<div class="prev-nav">
<a href="#" rel="prev">
<span>Previous</span>
Tips on Minimalist Design
</a>
</div>
<div class="next-nav">
<a href="#" rel="next">
<span>Next</span>
Less Is More
</a>
</div>
</div>
Основываясь на ваших комментариях, я предполагаю, что вы хотите получить два связанных поста, которые имеют тот же category
, что и текущий пост.
Если я прав, то один из методов, который вы можете использовать, это filter
поиск queryset
для того же category
, принадлежащего текущему посту, затем вы можете выбрать следующий и предыдущий посты текущего поста из полученного queryset
. Например:
def post_details(request, pk):
current_post = Post.objects.get(pk=pk) # retrieving the current post...
# filtering for related posts only by using the category of the current post
# using -> category_in=post.category.all() since it's a ManyToMany field
related_posts = Post.objects.filter(category_in=current_post.category.all())
# next -> get posts with id greater than the current post id, then get the first instance 'next post'
# previous -> get posts with id less than the current post id, then get the first instance 'previous post'
context = {
'post': current_post,
'next': related_posts.filter(id__gt=current_post.id).order_by('id').first(),
'previous': related_posts.filter(id__lt=current_post.id).order_by('-id').first()
}
return render(request, 'blog/post_detail.html', context)
Идеально, это должно сработать.
Небольшая рекомендация... Вместо использования Post.objects.get(pk=pk)
, я бы предложил использовать get_object_or_404()
, так как это обработает любую потенциальную ошибку, которую выкинет Post.objects.get(pk=pk)
. Итак, небольшое обновление...
from django.shortcuts import get_object_or_404
def post_details(request, pk):
current_post = get_object_or_404(Post, pk=pk) # retrieving the current post...
# the rest of the code follows...