Skip to content

Commit

Permalink
Building complex QuerySets to recommend similar posts
Browse files Browse the repository at this point in the history
  • Loading branch information
yahyaaly151989 committed Aug 24, 2023
1 parent 2dc68ee commit c0dcdd1
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
Binary file modified Module03/mysite/blog/__pycache__/views.cpython-311.pyc
Binary file not shown.
12 changes: 12 additions & 0 deletions Module03/mysite/blog/templates/blog/post/detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ <h1>{{ post.title }}</h1>
Share this post
</a>
</p>


<h2>Similar posts</h2>
{% for post in similar_posts %}
<p>
<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
</p>
{% empty %}
There are no similar posts yet.
{% endfor %}


{% with comments.count as total_comments %}
<h2>
{{ total_comments }} comment{{ total_comments|pluralize }}
Expand Down
8 changes: 7 additions & 1 deletion Module03/mysite/blog/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.core.mail import send_mail
from django.views.decorators.http import require_POST
from taggit.models import Tag
from django.db.models import Count

def post_list(request, tag_slug=None):
post_list = Post.objects.all()
Expand Down Expand Up @@ -46,7 +47,12 @@ def post_detail(request, year, month, day, post):
comments = post.comments.filter(active=True)
# Form for users to comment
form = CommentForm()
return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'form': form})

# List of similar posts
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts = Post.objects.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')
return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'form': form, 'similar_posts': similar_posts})

def post_share(request, post_id):
# Retrieve post by id
Expand Down
Binary file modified Module03/mysite/db.sqlite3
Binary file not shown.

0 comments on commit c0dcdd1

Please sign in to comment.