In the book that I am, reading so as to count the number of tags in common between multiple posts the Count
from django.db.models
is used. For tags the taggit
is used. But I am quite confused how this functionality is working
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts =Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]
In my case, I have several posts and each has two tags. Each post shares only one tag with other posts. I am getting the list of the ids of the tags that the post that I am interested in contains. Then according to that list, I am filtering out other posts. Then I am adding same_tags
parameter for all the posts, counting the tags
they have.
My confusion is here, as I said I have two tags in each post but magicaly here same_tag
is counting one which is the number of tags that post shares with the post of my interest. How this is happening?
Here is my test in the shell
>>> posts
[<Post: This is the other one >, <Post: Some content >, <Post: Other Post>,<Post: Temurs learning curv>]
>>> post = Post.objects.get(pk=1)
>>> post_tags_ids = post.tags.values_list('id', flat=True)
>>> post_tags_ids
[2, 3]
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts[0].tags.count()
2
>>> similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]
>>> similar_posts[0].tags.all()
[<Tag: jazz>, <Tag: temur>]
>>> similar_posts[0].same_tags
1
How I am getting one for the Count() while I have two tags?