Search code examples
pythonhtmldjangotags

Retrieving all posts by liked post's tags


I am trying to implement a feature in my Social Media WebApp . I am trying to get all tags posts according to user's liked posts

For Example ( In Brief ) :-

Suppose, user_1 liked a post and that post contains tags of #tag1 , #tag2 , #tag3. AND i am trying to show all the posts in a page that contains one of these tags which is liked by user.

models.py

class Post(models.Model):
    post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE)
    likes = models.ManyToManyField(User, related_name='post_like', blank=True)
    tags = TaggableManager()

views.py

def get_post(request,user_id):
    tags = Tag.objects.filter(post=id)
    posts = Post.objects.filter(likes__in=[user_id])

    context = {'posts':posts,'tagss':tagss}
    return render(request,'like_post.html', context)

like_post.html

{% for post in posts %}


{% for tag in post.tags.all %}

{{ tag }}

{% endfor %}


{% endfor %}

When i try to run this in browser then it only shows the posts done by me and its tags.

What have i tried :-

  • I tried also by i_contains=tags but this didn't worked for me.

  • I noticed a question yesterday about it BUT that question is deleted too.

  • I also tried this :-

      def get_like_related_post(request,user_id):
          post = get_object_or_404(Post,post_owner=user_id)
          posts = Tag.objects.filter(tag_id_in=post.likes.all)
    

BUT it is keep showing

get() returned more than one Post -- it returned 6!

I am new in Django AND I have no idea , how can i do it.

Any help would be Appreciated.

Thank You in Advance


Solution

  • You can try filtering on taggit.models.Tag to get the tags that are related to posts liked by the user and then filtering the posts on those tags. Which will be something like (Untested):

    from taggit.models import Tag
    
    
    def get_post(request,user_id):
        tags = Tag.objects.filter(post__likes=user_id).distinct()
        posts = Post.objects.filter(tags__in=tags).distinct()
        context = {'posts':posts,'tags':tags}
        return render(request,'like_post.html', context)