Skip to content

Commit cb291f5

Browse files
committed
Recommend similar posts
1 parent 13af7e9 commit cb291f5

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

mysite/apps/blog/templates/blog/post/detail.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@ <h1>{{ post.title }}</h1>
1313
Share this post
1414
</a>
1515
</p>
16+
<h2>Similar posts</h2>
17+
{% for post in similar_posts %}
18+
<p>
19+
<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
20+
</p>
21+
{% empty %}
22+
There are no similar posts yet.
23+
{% endfor %}
1624
{% with comments.count as total_comments %}
1725
<h2>
1826
{{ total_comments }} comment{{ total_comments|pluralize }}

mysite/apps/blog/views.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,21 @@ def post_detail(request, year, month, day, post):
6868
new_comment.save()
6969
else:
7070
comment_form = CommentForm()
71+
72+
# List of similar posts
73+
post_tags_ids = post.tags.values_list('id', flat=True)
74+
similar_posts = Post.published.filter(tags__in=post_tags_ids)\
75+
.exclude(id=post.id)
76+
similar_posts = similar_posts.annotate(same_tags=Count('tags'))\
77+
.order_by('-same_tags','-publish')[:4]
7178

7279
return render(request,
7380
'blog/post/detail.html',
7481
{'post': post,
7582
'comments': comments,
7683
'new_comment': new_comment,
77-
'comment_form': comment_form,})
84+
'comment_form': comment_form,
85+
'similar_posts': similar_posts})
7886

7987
def post_share(request, post_id):
8088
# Retrieve post by id

0 commit comments

Comments
 (0)